为什么我们需要新的Java日期/时间API?
Java的日期/时间类的定义并不一致,在java.util和java.sql的包中都有日期累,此外用于格式化和解析的类在java.text包中定义。
java.util.Date同时包含日期和时间,而java.sql.Date仅包含日期,将其纳入java.sql并不合理。
对于时间、时间戳、格式化以及解析,并没有明确定义的类。对于格式化和解析的需求,有java.text.DateFormat抽象类,但通常情况下,SimpleDateFormat类被用于此类需求。
日期类国际化支持的并不是很好。
Java8日期/时间API
不变性:新的日期/时间API中,所有的类都是不可变的,这对多线程环境有好处。
关注点分离:新的API将人可读的日期时间和机器时间(unix timestamp)明确分离,它为日期(Date)、时间(Time)、日期时间(DateTime)、时间戳(unix timestamp)以及时区定义了不同的类。
清晰:在所有的类中,方法都被明确定义用以完成相同的行为。举个例子,要拿到当前实例我们可以使用now()方法,在所有的类中都定义了format()和parse()方法,而不是像以前那样专门有一个独立的类。为了更好的处理问题,所有的类都使用了工厂模式和策略模式,一旦你使用了其中某个类的方法,与其他类协同工作并不困难。
实用操作:所有新的日期/时间API类都实现了一系列方法用以完成通用的任务,如:加、减、格式化、解析、从日期/时间中提取单独部分,等等。
Java日期/时间API包
Java日期/时间API包含以下相应的包。
java.time包:这是新的Java日期/时间API的基础包,所有的主要基础类都是这个包的一部分,如:LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration等等。所有这些类都是不可变的和线程安全的,在绝大多数情况下,这些类能够有效地处理一些公共的需求。
java.time.chrono包:这个包为非ISO的日历系统定义了一些泛化的API,我们可以扩展AbstractChronology类来创建自己的日历系统。
java.time.format包:这个包包含能够格式化和解析日期时间对象的类,在绝大多数情况下,我们不应该直接使用它们,因为java.time包中相应的类已经提供了格式化和解析的方法。java.time.temporal包:这个包包含一些时态对象,我们可以用其找出关于日期/时间对象的某个特定日期或时间,比如说,可以找到某月的第一天或最后一天。你可以非常容易地认出这些方法,因为它们都具有“withXXX”的格式。
java.time.zone包:这个包包含支持不同时区以及相关规则的类
Java日期/时间API示例
java.time.LocalDate
LocalDate是一个不可变的类,它表示默认格式(yyyy-MM-dd)的日期,
public static void main(String[] args) {
// 当前日期yyyy-MM-dd
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
// 创建一个日期
LocalDate localDate2 = LocalDate.of(2017, 10, 17);
System.out.println(localDate2);
// 获取指定时区的当前时间
LocalDate localDate3 = LocalDate.now(ZoneId.of("Asia/Kolkata"));
System.out.println(localDate3);
// 格林威治时间+天数
LocalDate localDate4 = LocalDate.ofEpochDay(365);
System.out.println(localDate4);
// 某年的第几天的日期
LocalDate localDate5 = LocalDate.ofYearDay(2017, 200);
System.out.println(localDate5);
}
java.time.LocalTime
LocalTime是一个不可变的类,它的实例代表一个符合人类可读格式的时间,默认格式是hh:mm:ss.zzz。
public static void main(String[] args) {
//当前时间
LocalTime time = LocalTime.now();
System.out.println("Current Time="+time);
// 创建当前时间
LocalTime specificTime = LocalTime.of(12,20,25,40);
System.out.println("Specific Time of Day="+specificTime);
// 获取指定时区当前时间
LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println("Current Time in IST="+timeKolkata);
// 当天多少秒的时间
LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
System.out.println("10000th second time= "+specificSecondTime);
}
java.time.LocalDateTime
LocalDateTime是一个不可变的日期-时间对象,它表示一组日期-时间,默认格式是yyyy-MM-dd-HH-mm-ss.zzz。它提供了一个工厂方法,接收LocalDate和LocalTime输入参数,创建LocalDateTime实例。
public static void main(String[] args) {
// 当前日期时间
LocalDateTime today = LocalDateTime.now();
System.out.println("Current DateTime="+today);
// 当前日期时间
today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("Current DateTime="+today);
// 指定时间日期时间
LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
System.out.println("Specific Date="+specificDate);
// 当前指定时区日期时间
LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println("Current Date in IST="+todayKolkata);
// 格林威治后多少分钟的日期时间
LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
System.out.println("10000th second time from 01/01/1970= "+dateFromBase);
}
java.time.Instant
Instant类是用在机器可读的时间格式上的,它以Unix时间戳的形式存储日期时间。
public static void main(String[] args) {
// 当前时间戳
Instant timestamp = Instant.now();
System.out.println("Current Timestamp = "+timestamp); // Current Timestamp = 2017-10-17T15:10:50.064Z
Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli()); // Specific Time = 2017-10-17T15:10:50.064Z
System.out.println("Specific Time = "+specificTime);
Duration thirtyDay = Duration.ofDays(30);
System.out.println(thirtyDay); // PT720H
}
日期API工具
大多数日期/时间API类都实现了一系列工具方法,如:加/减天数、周数、月份数,等等。还有其他的工具方法能够使用TemporalAdjuster调整日期,并计算两个日期间的周期。
public static void main(String[] args) {
LocalDate today = LocalDate.now();
// 根据当前日期获取其他日期
// 闰年
System.out.println("Year "+today.getYear()+" is Leap Year? "+today.isLeapYear());
// 在某个日期之前
System.out.println("Today is before 01/01/2015? "+today.isBefore(LocalDate.of(2015,1,1)));
// 根据LocalDate创建LocalDateTime
System.out.println("Current Time="+today.atTime(LocalTime.now()));
// 加多少天 多少周 多少月
System.out.println("10 days after today will be "+today.plusDays(10));
System.out.println("3 weeks after today will be "+today.plusWeeks(3));
System.out.println("20 months after today will be "+today.plusMonths(20));
// 减多少天 多少周 多少月
System.out.println("10 days before today will be "+today.minusDays(10));
System.out.println("3 weeks before today will be "+today.minusWeeks(3));
System.out.println("20 months before today will be "+today.minusMonths(20));
// 当天月第一天日期
System.out.println("First date of this month= "+today.with(TemporalAdjusters.firstDayOfMonth()));
// 当天年最后一天日期
LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
System.out.println("Last date of this year= "+lastDayOfYear);
旧的日期时间支持
旧的日期/时间类已经在几乎所有的应用程序中使用,因此做到向下兼容是必须的。这也是为什么会有若干工具方法帮助我们将旧的类转换为新的类,反之亦然。
public static void main(String[] args) {
//Date to Instant
Instant timestamp = new Date().toInstant();
//Now we can convert Instant to LocalDateTime or other similar classes
LocalDateTime date = LocalDateTime.ofInstant(timestamp,
ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
System.out.println("Date = "+date);
//Calendar to Instant
Instant time = Calendar.getInstance().toInstant();
System.out.println(time);
//TimeZone to ZoneId
ZoneId defaultZone = TimeZone.getDefault().toZoneId();
System.out.println(defaultZone);
//ZonedDateTime from specific Calendar
ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
System.out.println(gregorianCalendarDateTime);
//Date API to Legacy classes
Date dt = Date.from(Instant.now());
System.out.println(dt);
TimeZone tz = TimeZone.getTimeZone(defaultZone);
System.out.println(tz);
GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
System.out.println(gc);
}
Date与LocalDateTime、LocalDate、LocalTime互转
// 01. java.util.Date --> java.time.LocalDateTime
public void UDateToLocalDateTime() {
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
}
// 02. java.util.Date --> java.time.LocalDate
public void UDateToLocalDate() {
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalDate localDate = localDateTime.toLocalDate();
}
// 03. java.util.Date --> java.time.LocalTime
public void UDateToLocalTime() {
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalTime localTime = localDateTime.toLocalTime();
}
// 04. java.time.LocalDateTime --> java.util.Date
public void LocalDateTimeToUdate() {
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
}
// 05. java.time.LocalDate --> java.util.Date
public void LocalDateToUdate() {
LocalDate localDate = LocalDate.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
}
// 06. java.time.LocalTime --> java.util.Date
public void LocalTimeToUdate() {
LocalTime localTime = LocalTime.now();
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
}