java,API时间日期,新老对比
在java8以前:
有关时间日期的操作,Date;
日期、月份、天数相加减时,Calendar;
时间日期进行格式化时,SimpleDateFormat,DateFormath或其他子类。
缺点: 这些有关的时间日期操作对象,都是可变的、线程不安全的,代码繁琐,性能低。
java8提供新的时间日期操作:
LocalDate : 只含年月日的日期对象;
LocalTime :只含时分秒的时间对象;
LocalDateTime : 同时含有年月日时分秒的日期对象。
常用介绍:
ZoneId: 时区ID,用来确定Instant和LocalDateTime互相转换的规则
Instant: 用来表示时间线上的一个点(瞬时)
LocalDate: 表示没有时区的日期, LocalDate是不可变并且线程安全的
LocalTime: 表示没有时区的时间, LocalTime是不可变并且线程安全的
LocalDateTime: 表示没有时区的日期时间, LocalDateTime是不可变并且线程安全的
Clock: 用于访问当前时刻、日期、时间,用到时区
Duration: 用秒和纳秒表示时间的数量(长短),用于计算两个日期的“时间”间隔
Period: 用于计算两个“日期”间隔
优点 线程安全,代码简洁
使用示例
- 获取当前日期时间,yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、HH:mm:ss
LocalDateTime dateTime = LocalDateTime.now();
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
System.out.println(dateTime);
System.out.println(date);
System.out.println(time);
打印结果
2. 根据指定日期时间创建对象
LocalDateTime dateTime = LocalDateTime.of(2020,1,1,11,30,21);
LocalDate date = LocalDate.of(2020,1,1);
LocalTime time = LocalTime.of(11,30,21);
System.out.println(dateTime);
System.out.println(date);
System.out.println(time);
打印结果
3.时间日期相加减
LocalDateTime localDateTime = LocalDateTime.now();
//以下方法的参数都是long型,返回值都是LocalDateTime
LocalDateTime plusYearsResult = localDateTime.plusYears(2L);
LocalDateTime plusMonthsResult = localDateTime.plusMonths(3L);
LocalDateTime plusDaysResult = localDateTime.plusDays(7L);
LocalDateTime plusHoursResult = localDateTime.plusHours(2L);
LocalDateTime plusMinutesResult = localDateTime.plusMinutes(10L);
LocalDateTime plusSecondsResult = localDateTime.plusSeconds(10L);
System.out.println("当前时间是 : " + localDateTime + "\n"
+ "当前时间加2年后为 : " + plusYearsResult + "\n"
+ "当前时间加3个月后为 : " + plusMonthsResult + "\n"
+ "当前时间加7日后为 : " + plusDaysResult + "\n"
+ "当前时间加2小时后为 : " + plusHoursResult + "\n"
+ "当前时间加10分钟后为 : " + plusMinutesResult + "\n"
+ "当前时间加10秒后为 : " + plusSecondsResult + "\n"
);
//也可以以另一种方式来相加减日期,即plus(long amountToAdd, TemporalUnit unit)
//参数1 : 相加的数量, 参数2 : 相加的单位
LocalDateTime nextMonth = localDateTime.plus(1, ChronoUnit.MONTHS);
LocalDateTime nextYear = localDateTime.plus(1, ChronoUnit.YEARS);
LocalDateTime nextWeek = localDateTime.plus(1, ChronoUnit.WEEKS);
System.out.println("当前时间是 : " + localDateTime + "\n"
+ "nextYear : " + nextYear + "\n"
+ "nextMonth : " + nextMonth + "\n"
+ "nextWeek :" + nextWeek + "\n"
);
//日期的减法用法一样
打印结果:
4.获取日期中的年月日周时分秒
LocalDateTime localDateTime = LocalDateTime.now();
int dayOfYear = localDateTime.getDayOfYear();
int dayOfMonth = localDateTime.getDayOfMonth();
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println("今天是" + localDateTime + "\n"
+ "本年当中第" + dayOfYear + "天" + "\n"
+ "本月当中第" + dayOfMonth + "天" + "\n"
+ "本周中星期" + dayOfWeek.getValue() + "-即" + dayOfWeek + "\n");
//获取当天时间的年月日时分秒
int year = localDateTime.getYear();
Month month = localDateTime.getMonth();
int day = localDateTime.getDayOfMonth();
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
System.out.println("今天是" + localDateTime + "\n"
+ "年 : " + year + "\n"
+ "月 : " + month.getValue() + "-即 "+ month + "\n"
+ "日 : " + day + "\n"
+ "时 : " + hour + "\n"
+ "分 : " + minute + "\n"
+ "秒 : " + second + "\n"
);
打印结果
5.Instant与Date相互转化
Instant就相当于java8以前的Date
Instant instant = Instant.now();
Date date = Date.from(instant);
Instant instant2 = date.toInstant();
System.out.println(instant);
System.out.println(date);
System.out.println(instant2);
打印结果:
6.日期,时间间隔计算
//注意,当获取两个日期的间隔时,并不是单纯的年月日对应的数字相加减,而是会先算出具体差多少天,在折算成相差几年几月几日的
//计算两个日期的日期间隔-年月日
LocalDate date1 = LocalDate.of(2020, 1, 9);
LocalDate date2 = LocalDate.of(2019, 1, 9);
//内部是用date2-date1,所以得到的结果是负数
Period period = Period.between(date1, date2);
System.out.println(date1 + "与" +date2 + "相差间隔");
System.out.println("相差年数 : " + period.getYears());
System.out.println("相差月数 : " + period.getMonths());
System.out.println("相差日数 : " + period.getDays());
//还可以这样获取相差的年月日
System.out.println("-------------------------------");
long years = period.get(ChronoUnit.YEARS);
long months = period.get(ChronoUnit.MONTHS);
long days = period.get(ChronoUnit.DAYS);
System.out.println(date1 + "与" +date2 + "相差的年月日分别为 : " + years + "," + months + "," + days);
//计算两个时间的间隔
System.out.println("-------------------------------");
LocalDateTime date3 = LocalDateTime.now();
LocalDateTime date4 = LocalDateTime.of(2019, 1, 9, 22, 30, 10);
Duration duration = Duration.between(date3, date4);
System.out.println(date3 + " 与 " + date4 + " 间隔 " + "\n"
+ " 天 :" + duration.toDays() + "\n"
+ " 时 :" + duration.toHours() + "\n"
+ " 分 :" + duration.toMinutes() + "\n"
+ " 毫秒 :" + duration.toMillis() + "\n"
+ " 纳秒 :" + duration.toNanos() + "\n"
);
//注意,并没有获得秒差的,但既然可以获得毫秒,秒就可以自行获取了
打印结果:
7.使用时间戳Instant计算程序执行时间
Instant ins1 = Instant.now();
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
Instant ins2 = Instant.now();
Duration duration = Duration.between(ins1, ins2);
System.out.println("程序运行耗时为 : " + duration.toMillis() + "毫秒");
打印结果:
8.时间日期格式化(格式化后返回String类型)
LocalDateTime date1 = LocalDateTime.now();
//使用jdk自身配置好的日期格式
DateTimeFormatter formatter1 = DateTimeFormatter.ISO_DATE_TIME;
//自定义日期格式
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//formatter2.format(date1) 与 date1.format(formatter1) 调用相同;
String date1Str1 = date1.format(formatter1);
String date1Str2 = formatter2.format(date1);
System.out.println("使用jdk自身配置好的日期格式结果:" + date1Str1);
System.out.println("自定义日期格式结果:" + date1Str2);
打印结果:
注:自定义转化的格式一定要与日期类型对应
LocalDate只能设置仅含年月日的格式
LocalTime只能设置仅含时分秒的格式
LocalDateTime可以设置含年月日时分秒的格式
9.将时间字符串形式转化为日期对象
String datetime = "2020-01-01 21:27:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(datetime, formatter);
System.out.println("字符串转化为日期结果为:" + localDateTime);
打印结果:
注:格式的写法必须与字符串的形式一样
2018-01-13 21:27:30 对应 yyyy-MM-dd HH:mm:ss
20180113213328 对应 yyyyMMddHHmmss
否则会报运行时异常!
但要记住:得到的最终结果都是类似2018-01-13T21:27:30的格式
因为在输出LocalDateTime对象时,会调用其重写的toString方法。
@Override
public String toString() {
return date.toString() + 'T' + time.toString();
}
10.long毫秒值转换为日期
System.out.println("---------long毫秒值转换为日期---------");
DateTimeFormatter df= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String longToDateTime = df.format(LocalDateTime.ofInstant(
Instant.ofEpochMilli(System.currentTimeMillis()),ZoneId.of("Asia/Shanghai")));
System.out.println(longToDateTime);
打印结果: