4. Date类1:jdk1.8 之前
jdk1.8 之前的API:
- System类的
currentTimeMillis()
:获取当前系统时间- 两个Date类:
SimpleDateFormate
类:用于格式化、解析Calendar
日历类的使用:抽象类
4.1 两个Date类
时间戳:指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起到此刻的总秒数。
1)System类的currentTimeMillis():
- 获取当前时间对应的毫秒数,Long类型,时间戳;
- 毫秒数:指获取1970年1月1日 0时0分0秒,到现在的毫秒数
- 作用常用来作为时间差
2)两个Date类
|--java.util.Date
- 两个构造器:①无参构造;②long类型 有参构造
- 两个方法:①toString(); ②long getTime();
|----java.sql.Date
:对应数据库中的 date类型- 一个构造器:①long类型 有参构造
- 两个方法:①toString(); ②long getTime();
package com.lCommonClasses.eDateAndDateFormate;import java.util.Date;
/** Date:日期类* 1.|--java.util.Date* 2.|---java.sql.Date*/
public class Date1 {public static void main(String[] args) {/** 一、 java.util.Date* 构造器:一个有参构造器;一个无参构造器*///1.创建一个当前时间的Date对象Date date = new Date();//创建一个指定时间戳的Date实例;Sun Sep 15 13:26:28 CST 2013Date datePoint = new Date(1379222788828L);System.out.println(datePoint.toString());/*2.date: 当前系统时间date.getTime():获取1970年到现在的毫秒数*/System.out.println(date);System.out.println(date.getTime());/** 二、 java.sql.Date* 构造器:只有一个带参的构造器*/// 1.只有年-月-日: 2023-03-19java.sql.Date date2 = new java.sql.Date(System.currentTimeMillis());System.out.println(date2.toString());// 结果,2023-03-19System.out.println(date2.getTime());// 结果,1679629191418// 2.将字符串转化为日期String t = "2019-8-20";java.sql.Date date3 = java.sql.Date.valueOf(t);System.out.println(date3.getClass());// 结果,class java.sql.Date}
}
4.2 SimpeDateFormat
- java.text.SimpeDateFormat 类:是一个不与语言环境有关的方式来格式化和解析日期的具体的类
- 可以格式化:日期 --> 文本
- 可以解析:文本 --> 日期
构造器:
– SimpeDateFormat(): 默认的模式 和语言环境创建对象
– public SimpeDateFormat(String pattern): 该构造方法可以用参数 pattern指定的格式创建一个对象格式化:
日期 --> 字符串
– public String format(Date date): 该方法可以 格式化时间对象解析:
字符串 --> 日期
– public Date parse(String source): 从给定字符串的开始解析文本,以生成一个日期
/*** 默认格式* @throws ParseException 解析异常*/@Testpublic void test1() throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat();Date date = new Date();/* 1.`格式化: ` 日期 --> 字符串*/String strDate = sdf.format(date);System.out.println(strDate);//23-3-24 下午12:14/* 2.`解析: ` 字符串 --> 日期注意格式的书写,抛出解析异常:ParseException需要解析的字符串的格式,需要和默认格式保持一致*/Date date2 = sdf.parse("23-3-24 下午12:14");System.out.println(date2);//Fri Mar 24 12:14:00 CST 2023}
4.2.1 日期和时间模式
以下示例显示如何在美国区域设置中解释日期和时间模式。给定的日期和时间是美国太平洋时区的 2001-07-04 12:08:56 当地时间。我们可以进行自定义,比如:SimpeDateFormat (yyyy-MM-dd HH:mm:ss)
Date and Time Pattern | Result |
---|---|
"yyyy.MM.dd HH:mm:ss " | 2001.07.04 12:08:56 |
“yyyy.MM.dd G ‘at’ HH:mm:ss z” | 2001.07.04 AD at 12:08:56 PDT |
“EEE, MMM d, ''yy” | Wed, Jul 4, '01 |
“h:mm a” | 12:08 PM |
“hh ‘o’‘clock’ a, zzzz” | 12 o’clock PM, Pacific Daylight Time |
“K:mm a, z” | 0:08 PM, PDT |
“yyyyy.MMMMM.dd GGG hh:mm aaa” | 02001.July.04 AD 12:08 PM |
“EEE, d MMM yyyy HH:mm:ss Z” | Wed, 4 Jul 2001 12:08:56 -0700 |
“yyMMddHHmmssZ” | 010704120856-0700 |
“yyyy-MM-dd’T’HH:mm:ss.SSSZ” | 2001-07-04T12:08:56.235-0700 |
“yyyy-MM-dd’T’HH:mm:ss.SSSXXX” | 2001-07-04T12:08:56.235-07:00 |
“YYYY-'W’ww-u” | 2001-W27-3 |
4.2.2 日期 字母含义
定义了以下模式字母(保留从“A”到“Z”和从“a”到“z”的所有其他字符):
Letter | Date or Time Component | Presentation | Examples |
---|---|---|---|
G | Era designator | Text | AD |
y | Year | Year | 1996; 96 |
Y | Week year | Year | 2009; 09 |
M | Month in year (context sensitive) | Month | July; Jul; 07 |
L | Month in year (standalone form) | Month | July; Jul; 07 |
w | Week in year | Number | 27 |
W | Week in month | Number | 2 |
D | Day in year | Number | 189 |
d | Day in month | Number | 10 |
F | Day of week in month | Number | 2 |
E | Day name in week | Text | Tuesday; Tue |
u | Day number of week (1 = Monday, …, 7 = Sunday) | Number | 1 |
a | Am/pm marker | Text | PM |
H | Hour in day (0-23) | Number | 0 |
k | Hour in day (1-24) | Number | 24 |
K | Hour in am/pm (0-11) | Number | 0 |
h | Hour in am/pm (1-12)、Number | 12 | |
m | Minute in hour | Number | 30 |
s | Second in minute | Number | 55 |
S | Millisecond | Number | 978 |
z | Time zone | General time zone | Pacific Standard Time; PST; GMT-08:00 |
Z | Time zone | RFC 822 time zone | -0800 |
X | Time zone | ISO 8601 time zone | -08; -0800; -08:00 |
4.3 java.util.Calender
日历类(建议使用)
1)Date类的 API大部分被废弃了,替换为Calender
2)
Calendar
类是一个抽象类,主要用来完成日期字段之间相互操作的功能;
4.3.1 获取实例和常用方法
3) 获取Calendar实例的方法:
Calendar.getInstance()
方法4)常用方法:
- get(int field)
- set(int field, int amount)
- add(int field, int amount)
- getTime(): Calendar -->Date
- setTime(); 使用指定 Date重置 Calendar
package com.lCommonClasses.eDateAndDateFormate;
import org.junit.Test;
import java.util.*;
/*** Calendar 日历类:也是一个抽象类,需要new它的子类* Calendar的实例化 和常用方法*/
public class Calendar1 {@Testpublic void test1() {/**1.使用 Calendar的静态方法 getInstance()来实例化底层调用的还是实例化 Calendar的子类 GregorianCalendar*/Calendar calendar = Calendar.getInstance();// 结果,class java.util.GregorianCalendarSystem.out.println(calendar.getClass());/**2.1 get(int field) 获取年、月、日;月是从0开始的 */System.out.println(calendar.get(Calendar.MARCH) + 1);System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//获取当前月最大天数System.out.println("get(,):" + calendar.getActualMaximum(Calendar.DATE));/**2.2 set(int field, int amount) *///月份自动 +1,即实际值是:4calendar.set(Calendar.MONTH, 3);calendar.set(Calendar.DAY_OF_MONTH, 16);System.out.println(calendar.get(Calendar.MONTH));System.out.println(calendar.get(Calendar.DAY_OF_MONTH));/**2.3 add(int field, int amount) */calendar.add(Calendar.DAY_OF_MONTH, 3);calendar.add(Calendar.DAY_OF_MONTH, -5);System.out.println("add(,):" + calendar.get(Calendar.DAY_OF_MONTH));/**2.4 getTime(); Calendar -->Date */Date date = calendar.getTime();// 日期类System.out.println(date);/**2.5 setTime(); 使用指定 Date重置 Calendar */Date date1 =new Date();calendar.setTime(date1);// 日期类转日历类System.out.println(calendar.get(Calendar.MONTH));System.out.println(calendar.get(Calendar.DAY_OF_MONTH));}
}
4.3.2 常量含义意义
int field | 表示的意义 |
---|---|
Calendar.YEAR | 年份 |
Calendar.MONTH | 月份 |
Calendar.DATE | 日期 |
Calendar.DAY_OF_MONTH | 日期,和上面的字段意义相同 |
Calendar.HOUR | 12小时制的小时 |
Calendar.HOUR_OF_DAY | 24小时制的小时 |
Calendar.MINUTE | 分钟 |
Calendar.SECOND | 秒 |
Calendar.DAY_OF_WEEK | 星期几 |
4.3.3 练习:util.Date ->sql.Date
练习1:将java.util.Date的实例转换为 java.sql.Date的实例
思路:寻找他们的相同点:时间戳
@Testpublic void test1(){Date date1 = new Date();/* 错误实例:ClassCastExceptionjava.sql.Date date2 = (java.sql.Date) date1;System.out.println(date2);*//* 正确示例:寻找相同点(时间戳)*/java.sql.Date date2 = new java.sql.Date(date1.getTime());System.out.println(date2);// 结果,2023-03-24}
4.3.4 日期字符串 保存到数据库
拓展2:将控制台获取的年月日(比如:2022-10-01)的字符串数据,保存在数据库中。
简化:得到 java.sql.Date的对象,此对象对应的时间为:2022-10-01
分析:字符串(解析)–> java.util.Date–> java.sql.Date
@Testpublic void test2() throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String timeStr="2022-10-01";// 将 timeStr解析为 java.util.DateDate date1 = sdf.parse(timeStr);// 转换为 java.sql.Datejava.sql.Date date2 = new java.sql.Date(date1.getTime());System.out.println(date2);// 默认的调用的是toString()方法System.out.println(date2.toString());// 结果,2022-10-01}
4.4 Jdk1.8的日期类
Date和 Calendar面临的问题:
- 可变性:像日期和时间这样的类应该是不可变的;
- 偏移性:Date中的年份是从1900开始的,而且月份是从 0开始的;
- 格式化:格式化只对 Date有用,Calendar则不行;
- 它们是线程不安全的,也不能处理闰秒。
总结:对日期和时间的操作,一直是Java程序员最痛苦的地方之一。
第三次引入的API是成功的,并且Jdk1.8引入的java.time API
已经纠正了过去的缺陷,将来很长一段时间它都会为我们提供服务。
jdk1.8的日期时间API包含
java.time
- 包含值对象的基础包java.time.chrono
- 提供对不同的日历系统的访问java.time.format
- 格式化和解析 时间和日期java.time.temporal
- 包括底层框架和扩展特性java.time.zone
- 包含时区支持的类- 常用的有基础包、format包,尽管有68个新的公开类型,但是常用的只有三分之一。
属性 | 含义说明 |
---|---|
Instant | 代表时间相当于Date |
LocalDate | 本地日期,比如:2023-01-14 |
LocalTime | 本地时间,比如:12:20:30 |
LocalDateTime | 本地日期时间,比如:2022-01-14 12:20:30 |
ZonedDateTime | 时区,(包含时区的完整日期时间) |
Duration | 持续时间 |
Period | 代表时间段 |
ZoneOffset | 代表时区偏移量,比如+8:00 |
Clock | 代表时钟,比如获取美国纽约的时间 |
DateTimeFormatter | 日期和字符串格式转换 |
4.4.1 LocalDate、LocalTime、LocalDateTime
LocalDate、LocalTime、LocalDateTime–>类似于 Calender
- 实例化:now()、of(xx,xx,xx)
- 方法:get()、withXxx()设置、plusXxx()添加、minusXxx()减去、
方法 | 描述 |
---|---|
static LocalDate now() | 静态方法,根据当前时间创建对象/ 指定时区的对象 |
static LocalDate of(int year, Month month, int dayOfMonth) | 静态方法,根据指定日期/ 时间创建对象 |
getDayOfMonth()/ getDayOfYear() | 获取 月份(1~31)里/ 一年里的某天字段(1~366) 。 |
getDayOfWeek() | 获取 星期字段,这是一个枚举。 |
getMonth() | 使用枚举获取月份字段。 |
getMonthValue()/ getYear() | 获取 从 1 到 12 的月份字段/ 获取年份字段 |
getHour()/ getMinute()/ getSecond() | 获取 当前对象对应的时、分、秒字段。 |
withDayOfMonth()/ withDayOfYear()/ withMonth()/ withYear() | 将月份天数、年份天数、月份、年份设置 为指定的值,并返回新的对象 |
with(TemporalAdjuster adjuster) | 将当前日期时间设置 为校对器指定的日期时间 |
plusHours()/ plusDays()/ plusWeeks()/ plusMonths()/ plusYears() | 向当前对象 添加 几个小时、几天、几周、几月、几年 |
minusHours()/ minusDays()/ minusWeeks()/ minusMonths()/ minusYears() | 从当前对象减去 几个小时、几天、几周、几月、几年 |
plus(TemporalAmount t)/ minus(TemporalAmount t) | 添加或减少 一个 Duration(期间) 或Period(时期) |
isBefore()/ isAfter() | 比较两个 LocalDate |
isLeapYear() | 判断是否为 闰年 |
format(DateTimeFormatter t) | 格式化本地日期、时间,返回一个字符串 |
parse(CharSequence text) | 将指定格式的字符串解析为日期、时间 |
/** Jdk1.8的 API1. * LocalDate、LocalTime、LocalDateTime*/@Testpublic void test1(){/*1. static LocalDate now():获取当前日期和时间对应的实例 */LocalDate localDate = LocalDate.now();LocalTime localTime = LocalTime.now();LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDate);//2023-03-24System.out.println(localTime);//15:56:17.730System.out.println(localDateTime);//2023-03-24T15:56:17.730/*2. static LocalDate of(int year, Month month, int dayOfMonth):获取指定的日期、时间对应的实例*/LocalDate localDate1 = LocalDate.of(2022, 10, 01);LocalDateTime localDateTime1 = LocalDateTime.of(2021, 10, 01, 12, 25);System.out.println(localDate1);//2022-10-01System.out.println(localDateTime1);//2021-10-01T12:25}/** 1.2 getXxx() 获取;withXxx()设置;plusXxx()添加*/@Testpublic void test2(){/*1. getDayOfMonth() 获取 */LocalDateTime localDateTime1 = LocalDateTime.now();System.out.println(localDateTime1.getDayOfMonth());//24/**体现了不可变性*//*2. withDayOfMonth(int i) 设置 */LocalDateTime localDateTime2 = localDateTime1.withDayOfMonth(12);System.out.println(localDateTime1);//2023-03-24T16:57:05.096System.out.println(localDateTime2);//2023-03-12T16:57:05.096/*3. plusXxx() 添加 */LocalDateTime localDateTime3 = localDateTime1.plusDays(5);LocalDateTime localDateTime4 = localDateTime2.plusDays(-5);System.out.println(localDateTime1);//2023-03-24T17:17:07.588System.out.println(localDateTime3);//2023-03-29T17:17:07.588System.out.println(localDateTime4);//2023-03-07T17:17:07.588}
4.4.2 Instant:瞬时;类似Date
- Instant:时间线上的一个瞬时点。这可能被用来记录应用程序中的事件时间戳。
java.time.Instant
:时间线上的一点,而不需要任何上下文信息(例如:时区)。它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的秒数
。- 应用场景:订单号的生成
- 实例化:now()、ofEpochMilli(xx, xx, xx)
- 方法:toEpochMilli()
方法 | 描述 |
---|---|
now() | 静态方法,返回默认UTC时区的 Instant类的对象 |
ofEpochMilli(long epochMilli) | 静态方法,返回在 “1970-01-01 00:00:00”基础上加上指定毫秒数之后的 Instant类的对象 |
toEpochMilli() | 返回从 “1970-01-01 00:00:00”到此刻的毫秒数,即为时间戳 |
- 中国大陆、中国香港、中国澳门、中国台湾、蒙古国、新加坡、马来西亚时差均为+8,也就是UTC+8
instant.atOffset(ZoneOffset.ofHours(8));
时区偏移量
/** Jdk1.8的 API2. Instant */@Testpublic void test3(){// 1.now()Instant instant1 = Instant.now();System.out.println(instant1);//2023-03-24T09:56:39.591Z// 2.了解 atOffset(ZoneOffset.ofHours(8))OffsetDateTime instant2 = instant1.atOffset(ZoneOffset.ofHours(8));System.out.println(instant2);//2023-03-24T17:56:39.591+08:00//3.ofEpochMilli(long Milli)-->类似于DateInstant instant3 = Instant.ofEpochMilli(124578986532L);System.out.println(instant3);//1973-12-12T21:16:26.532Z//4.toEpochMilli() 获取时间戳long milliTime = instant1.toEpochMilli();System.out.println(milliTime);//1679652614997long time = new Date().getTime();System.out.println(time);//1679652615103}
4.4.3 DateTimeFormatter
1)DateTimeFormatter—>类似于 SimpleDateFormate:用于日期的格式化和 解析
- DateTimeFormatter主要是对LocalDate、LocalTime、LocalDateTime进行格式化、解析
- SimpleDateFormate是对 Date进行格式化、解析
自定义的格式。如:ofPattern(“yyyy-MM-dd HH:mm:ss”)
方法 | 描述 |
---|---|
ofPattern(String pattern) | 静态方法,返回一个指定字符串格式的 DateTimeFormatter |
format(localDateTime) | 格式化日期 |
parse(“2023/03/24 19:46:27”) + from(temporalAccessor) | 解析日期、时间字符串 |
/**Jdk1.8的 API3. DateTimeFormatter*/@Testpublic void test4(){//自定义格式,如:ofPattern("yyyy/MM/dd HH:mm:ss")DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");//格式化时间:日期、时间 -->字符串LocalDateTime localDateTime = LocalDateTime.now();String strDateTime = dateTimeFormatter.format(localDateTime);System.out.println(strDateTime);//2023/03/24 19:46:27//解析:字符串 -->日期、时间TemporalAccessor temporalAccessor = dateTimeFormatter.parse("2023/03/24 19:46:27");System.out.println(temporalAccessor);//{},ISO resolved to 2023-03-24T19:46:27//转化格式LocalDateTime localDateTime1 = LocalDateTime.from(temporalAccessor);System.out.println(localDateTime1);//2023-03-24T19:46:27}
4.4.4 其他API
4.1 ZoneId、ZonedDateTime(了解)
1、指定时区日期时间:ZondId、ZonedDateTime
- ZoneId:包含了所有的时区信息,一个时区的ID
- ZonedDateTime:一个在 ISO-8601 日历系统市区的日趋时间
其中每个时区都对应一个ID,地区ID都为 “{区域}/{城市}” 的格式,如:Asia/Shanghai 等 - 常见时区:
Asia/Shanghai
UTC
America/New_York
- 可以通过 ZoneId获取所有可用的时区ID:
/*** 1. 时区相关:ZoneId、ZonedDateTime*/@Testpublic void test1(){/*需要知道一些时区ID ;Set<String>是一个集合,容器*/Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();//快捷模板for (String availableZoneId : availableZoneIds) {System.out.println(availableZoneId);}}@Testpublic void test2(){ZonedDateTime t1 = ZonedDateTime.now();System.out.println(t1);ZonedDateTime t2 = ZonedDateTime.now(ZoneId.of("America/New_York"));System.out.println(t2);}
4.2 持续日期/时间:Period和 Duration(了解)
Period: 日期间隔,用于计算两个 “日期” 间隔
Duration:持续时间,用于计算两个 “时间” 间隔
@Testpublic void test3() {LocalDate nowTime = LocalDate.now();LocalDate oldTime = LocalDate.of(2018, 8, 15);Period between = Period.between(nowTime, oldTime);System.out.println(between);System.out.println("相差年数:" + between.getYears());// 相差年数:-4System.out.println("相差月数:" + between.getMonths());// 相差月数:-7System.out.println("相差日数:" + between.getDays());// 相差日数:-9System.out.println("相差总数:" + between.toTotalMonths());// 相差总月数:-55}@Testpublic void test4() {LocalDateTime t1 = LocalDateTime.now();LocalDateTime t2 = LocalDateTime.of(2018,10,01,0,0,0);Duration between = Duration.between(t1, t2);System.out.println(between);System.out.println("相差天数:" + between.toDays());System.out.println("相差小时数:" + between.toHours());System.out.println("相差分钟数:" + between.toMinutes());System.out.println("相差秒数:" + between.getSeconds());System.out.println("相差毫秒数:" + between.toMillis());System.out.println("相差纳秒数:" + between.toNanos());System.out.println("不够一秒的纳秒数:" + between.getNano());}
- Duration,用于计算两个 “时间” 间隔,以秒和纳秒为基准:
@Testpublic void test5() {LocalTime time1 = LocalTime.now();LocalTime time2 = LocalTime.of(15, 23, 30);// between: 日期间隔,返回 Duration对象,表示两个时间的间隔Duration duration = Duration.between(time1, time2);System.out.println(duration);// 结果,PT-5H-30M-48.355SSystem.out.println(duration.getSeconds());// 结果,-19849System.out.println(duration.getNano());// 结果,645000000LocalDateTime localDateTime1 = LocalDateTime.of(2016, 6, 6, 12, 32, 30);LocalDateTime localDateTime2 = LocalDateTime.of(2017, 6, 6, 12, 32, 30);Duration duration1 = Duration.between(localDateTime1, localDateTime2);System.out.println(duration1.toDays());// 结果,365}
- Period,用于计算两个 “日期” 间隔,以年、月、日衡量:
@Testpublic void test6() {LocalDate now = LocalDate.now();LocalDate date = LocalDate.of(2035, 10, 24);Period period = Period.between(now, date);System.out.println(period);// 结果,P12Y7MSystem.out.println(period.getYears());// 结果,12System.out.println(period.getMonths());// 结果,7System.out.println(period.getDays());// 结果,0Period period1 = period.withYears(2);System.out.println(period1);// 结果,P2Y7M}
4.3 Clock(了解)
Clock:使用时区提供对当前即时、日期和时间的访问的时钟
4.4 TemporalAdjuster时间校正器
- TemporalAdjuster,时间校正器。有时我们需要可能获取。如:将日期调整到 “下一个工作日” 等;
- TemporalAdjusters:该类通过静态方法(firstDayOfXxx()、lastDayOfXxx()、nextXxx())提供了大量的常用 TemporalAdjuster的实现。
package com.lCommonClasses.eDateAndDateFormate;
import org.junit.Test;
import java.time.*;
import java.time.temporal.*;
public class TimeJdk8_4 {@Testpublic void test1(){//获取当前日期的下一个周日是哪天?TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);System.out.println(localDateTime);//获取下一个工作日是哪天?LocalDate workDate = LocalDate.now().with(new TemporalAdjuster() {@Overridepublic Temporal adjustInto(Temporal temporal) {LocalDate date = (LocalDate) temporal;if (date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){return date.plusDays(3);}else if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){return date.plusDays(2);}else {return date.plusDays(1);}}});System.out.println("下一个工作日是:"+workDate);}
}
4.4.5 与传统日期处理的转换
类 | To 遗留类 | From 遗留类 |
---|---|---|
java.time.Instant与 java.util.Date | Date.from( instant) | date.toInstant() |
java.time.Instant与 java.sql.Timestamp | Timestamp.from( instant) | timestamp.toInstant() |
java.time.ZonedDateTime与 java.util.GregorianCalendar | GregorianCalendar.from( ZonedDateTime) | cal.toZonedDateTime() |
java.time.LocalDate与 java.sql.Time | Date.valueOf( localDate) | date.toLocalDate() |
java.time.LocalTime与 java.sql.Time | Date.valueOf( localDate) | date.toLocalDate() |
java.time.LocalDateTime与 java.sql.Timestamp | Timestamp.valueOf( localDateTime) | timestamp.toLocalDateTime() |
java.time.ZoneId与 java.util.TimeZone | Timezone.getTimeZone( id) | timeZone.toZoneId() |
java.time.format.DateTimeFormatter与 java.text.DateFormat | formatter.toFormat() | 无 |
4.4.6 练习题:获取百天日期
package com.lCommonClasses.eDateAndDateFormate;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;public class TimeInterview1 {/*** 1.使用 Calendar获取当前时间,把这个时间设置为你的生日,* 再获取你的百天(出生后第100天)日期*/@Testpublic void test1(){Calendar calendar = Calendar.getInstance();Date date = calendar.getTime();System.out.println("出生日期:" + date);calendar.add(Calendar.DAY_OF_YEAR,100);Date hundredDay = calendar.getTime();System.out.println("百天日期是:" + hundredDay);}/*** 2.使用 LocalDateTime获取当前时间,把这个时间设置为你的生日,* 再获取你的百天(出生后第100天)日期*/@Testpublic void test2(){LocalDateTime date = LocalDateTime.now();System.out.println("出生日期:" + date);LocalDateTime hundredDay = date.plusDays(100);System.out.println("百天日期是:" + hundredDay);}
}
4.5 日期互转
4.5.1 long与Date、Calendar
package com.lCommonClasses.dateAndDateFormate;import java.util.Calendar;
import java.util.Date;/** DateReversal日期互转1: long与 Date、Calendar */
public class DateReversal1 {public static void main(String[] args) {/** 1.1 long与 Date */Date date = new Date();long time = date.getTime();System.out.println(date);System.out.println(time);/** 1.2 long与Calendar */Calendar calendar = Calendar.getInstance();calendar.set(Calendar.YEAR,2021);calendar.set(Calendar.MONTH,11);calendar.set(Calendar.DAY_OF_MONTH,6);long timeInMillis = calendar.getTimeInMillis();System.out.println(calendar);System.out.println(timeInMillis);}
}
4.5.2 Date与Calendar互转
package com.lCommonClasses.dateAndDateFormate;import java.util.Calendar;
import java.util.Date;/** DateReversal日期互转2: Date与 Calendar互转 */
public class DateReversal2 {public static void main(String[] args) {/**2.1 Date转 Calendar*/Date date = new Date();Calendar calendar = Calendar.getInstance();calendar.setTime(date);// 结果,Sun Mar 19 20:36:20 CST 2023System.out.println(calendar.getTime());/** 2.1 Calendar转 Date */Calendar c = Calendar.getInstance();c.set(Calendar.YEAR,2000);//月份自动 +1,即实际值是:12c.set(Calendar.MONTH,11);c.set(Calendar.DAY_OF_MONTH,22);c.add(Calendar.DAY_OF_MONTH,2);// 结果,Sun Dec 24 21:14:33 CST 2000System.out.println(c.getTime());}
}
4.5.3 Date与String互转
package com.lCommonClasses.dateAndDateFormate;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/** DateReversal日期互转3: Date与 String互转 */
public class DateReversal3 {public static void main(String[] args) {/**3.1 Date转String*/SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");String dateStr=sdf.format(new Date());System.out.println(dateStr);// 结果,2023-03-19/**3.2 String转 Date: 注意格式必须一致*/String str="2022-11-06";SimpleDateFormat sDF= new SimpleDateFormat("yyyy-MM-dd");Date date = null;try {date = sDF.parse(str);System.out.println(date);} catch (ParseException e) {System.out.println("String转 Date错误");}}
}
4.5.4 Calendar与String互转
package com.lCommonClasses.dateAndDateFormate;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;/** DateReversal日期互转4: Calendar与 String互转 */
public class DateReversal4 {public static void main(String[] args) throws ParseException {/** 4.1 Calendar 转化成 String*/Calendar c = Calendar.getInstance();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String str = sdf.format(c.getTime());// String str = sdf.format(new Date());System.out.println(str);/** 4.2 String (先转Date,再)转化成 Calendar*/String str1="2020-11-6";SimpleDateFormat sdf1= new SimpleDateFormat("yyyy-MM-dd");Date date =sdf1.parse(str1);c.setTime(date);System.out.println(c.getTime());}
}