java8新特性之time
java 8提供了java.time包来表示、操作时间。主要涉及到了date、time、instant、duration、timezone的概念。这些时间类都是基于ISO日历系统的。这些时间类都是不可变的,因此也是线程安全的。
在java8之前,时间类有java.util下的Date、Calendar等类提供。但是由于它们类型不安全、线程不安全(可变的)、易出bug(比如不常用的月份编号方式)等问题,导致这些遗留类不在常用。
废话不说,直接上代码
public void testLocalDateTime()
{
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = currentTime.atZone(zone).toInstant();
System.out.println("当前时间转毫秒: " + instant.toEpochMilli());
LocalDate date1 = currentTime.toLocalDate();
System.out.println("date1: " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("月: " + month + ", 日: " + day + ", 秒: " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
System.out.println("date2: " + date2);
Period period2 = Period.between(date1, date2.toLocalDate());
System.out.println(period2.getYears());
System.out.println(period2.getMonths());
System.out.println(period2.toTotalMonths());
LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
System.out.println("date3: " + date3);
LocalTime date4 = LocalTime.of(22, 15);
System.out.println("date4: " + date4);
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
public void testZonedDateTime()
{
ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
System.out.println("date1: " + date1);
ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("当期时区: " + currentZone);
}