ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java8(七) 新的DateTime API

2020-07-29 06:31:46  阅读:327  来源: 互联网

标签:Instant localDateTime time1 DateTime start API LocalDateTime now Java8


新的日期时间API

1 日期/时间

LocalDate:没有时区的日期

LocalTime:没有时区的时间

LocalDateTime:没有时区的日期时间

ZonedDateTime:有时区的日期时间

时区/ZoneId

ZoneId.getAvailableZoneIds()获取所有可用的ZoneId。

偏移量/ZoneOffset

偏移量指的是偏移UTC时区的时分秒。

如:+08:00的意思时超前于UTC八个小时,而 -05:45 意思是落后于UTC五小时四十五分钟。

因为有着夏/冬令时的区分,所以偏移量会发生变化。

获取日期时间信息
LocalDateTime localDateTime = LocalDateTime.now();
//很多,不一一写出来
localDateTime.getXXX();
日期时间调整
  • 加减
LocalDateTime localDateTime = LocalDateTime.now();
//很多,不一一写出来
localDateTime.minusXXX();
  • 修改
LocalDateTime localDateTime = LocalDateTime.now();
//很多,不一一写出来
localDateTime.withXXX();
日期时间比较
LocalDateTime time1 = LocalDateTime.now();
LocalDateTime time2 = time1.minusDays(1);
int compare = time1.compareTo(time2);
boolean after = time1.isAfter(time2);
boolean before = time1.isBefore(time2);
boolean equal = time1.isEqual(time2);
格式化
LocalDateTime time = LocalDateTime.now();
time.format(DateTimeFormatter.ofPattern("yyyyMM"));
TemporalAdjuster
LocalDateTime time = LocalDateTime.now();
time.with(TemporalAdjusters.xxx());
//dayOfWeekInMonth() – 一周中的某一天,例如,三月中第二个星期二
//firstDayOfMonth() – 当前月的第一天
//firstDayOfNextMonth() – 下一个月的第一天
//firstDayOfNextYear() – 下一年的第一天
//firstDayOfYear() – 当年的第一天
//lastDayOfMonth() – 当月的最后一天
//nextOrSame() – 下一次或当天发生的一周中的某天

2 时间戳与时间段

Instant

时间戳。

表示Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的时间。

Instant instant = Instant.now();
long epochSecond = instant.getEpochSecond();//秒数
long l = instant.toEpochMilli();//毫秒数
System.out.println(epochSecond);
System.out.println(l);
Period

基于日期的时间段。

LocalDate start = LocalDate.of(2020, 7, 28);
LocalDate end = LocalDate.of(2020, 7, 29);
 
Period period = Period.between(start, end);
boolean negative = period.isNegative();//判断start end的大小
System.out.println(period);//格式为P-1Y-1M-30D
//基于年与日的时间段
Duration

基于时间的时间段。

Instant start = Instant.parse("2020-07-09T06:07:30.00Z");
Instant end = Instant.parse("2019-05-07T11:12:37.20Z");

Duration duration = Duration.between(start, end);
boolean negative = duration.isNegative();//判断start end的大小
System.out.println(duration);//格式为PT-10290H-54M-52.8S
//基于时分秒的时间段

标签:Instant,localDateTime,time1,DateTime,start,API,LocalDateTime,now,Java8
来源: https://www.cnblogs.com/lyldelove/p/13394909.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有