java时间处理相关的类

1、java7---Calendar

Calendar类使用其静态的getInstance()方法获取一个日历实例,该实例为当前的时间;如果想改变时间,可以通过其setTime方法传入一个Date对象,即可获得Date对象所表示时间的Calendar对象

2、java8---Period

通过调用Period类的静态方法between,传入两个待比较的LocalDate对象today与oldDate,得到的Period的对象p中就包含了today与oldDate两个日期相差的年、月、日信息,可以通过p.getYears()等方法取出l

3、java8---Duration

Duration与Period相对应,Period用于处理日期,而Duration计算时间差还可以处理具体的时间,也是通过调用其静态的between方法,该方法的签名是between(Temporal startInclusive, Temporal endExclusive),因此可以传入两个Instant的实例(Instant实现了Temporal接口),并可以以毫秒(toMillis)、秒(getSeconds)等多种形式表示得到的时间差.
例如:

Instant inst1 = Instant.now(); //当前的时间
System.out.println("Inst1:" + inst1);
Instant inst2 = inst1.plus(Duration.ofSeconds(10)); //当前时间+10秒后的时间
System.out.println("Inst2:" + inst2);
Instant inst3 = inst1.plus(Duration.ofDays(120)); //当前时间+120天后的时间
System.out.println("inst3:" + inst3);

System.out.println("以毫秒计的时间差:" + Duration.between(inst1, inst2).toMillis());

System.out.println("以秒计的时间差:" + Duration.between(inst1, inst3).getSeconds());

几个转换:

// date与instant的相互转化
Instant now = Instant.now();
Date date = Date.from(now);
Instant instant = date.toInstant();
// LocalDateTime代替Calendar
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
int year = localDateTime.getYear();
int month = localDateTime.getMonthValue();
int dayOfMonth = localDateTime.getDayOfMonth();
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
// DateTimeFormatter代替SimpleDateFormat
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Date格式化成String
String format = dateTimeFormatter.format(localDateTime);
LocalDateTime parse = LocalDateTime.parse(format, dateTimeFormatter);
ZoneOffset offset = OffsetDateTime.now().getOffset();
Instant instant2 = parse.toInstant(offset);
// 从String获得Date
Date from = Date.from(instant2);

4、java8---ChronoUnit

ChronoUnit类可用于在单个时间单位内测量一段时间,例如天数或秒。
以下是使用between()方法来查找两个日期之间的区别的示例。

LocalDate startDate = LocalDate.of(1993, Month.OCTOBER, 19);

System.out.println("开始时间 : " + startDate);

LocalDate endDate = LocalDate.of(2017, Month.JUNE, 16);

System.out.println("结束时间 : " + endDate);

long daysDiff = ChronoUnit.DAYS.between(startDate, endDate);

System.out.println("两天之间的差在天数 : " + daysDiff);

 

5、比较

传统的SimpleDateFormat和Java 7中的Calendar在使用的时候需要自己写一个计算时间差的逻辑,比较麻烦,但是却比较灵活,方便根据自己具体的需求来定制(比如,我想两个日期的天数差15天就算满一个月,不满15天不算一个月,如2020-01-04到2020-02-20,算2个月的时间差);而Java 8中的几个计算时间差的类更加方便、精确,可以以不同的单位表示得到的时间差,但要注意几个类所包含的时间信息的区别:

System.out.println(LocalDate.now()); //只包含日期信息
System.out.println(LocalTime.now()); //只包含时间信息
System.out.println(LocalDateTime.now()); //包含日期、时间信息

posted @ 2020-03-26 12:04  酒哥-颢远  阅读(201)  评论(0编辑  收藏  举报