Java 8日期 – LocalDate,LocalDateTime,Instant

日期时间 API 是 Java 8 发布的最重要的功能之一。Java 一直缺乏一致的日期和时间处理方法,而 Java 8 的日期时间 API 则是核心 Java API 的一项受欢迎的补充。

我们为什么需要新的 Java 日期时间 API?

在我们开始了解 Java 8 日期时间 API 之前,让我们看看为什么我们需要一个新的 API。现有的 Java 日期和时间相关类存在一些问题,其中一些问题包括:

  • Java 日期时间类的定义不一致,我们在 java.util 和 java.sql 包中都有日期类。而且,格式化和解析类是在 java.text 包中定义的。
  • java.util.Date 类同时包含日期和时间值,而 java.sql.Date 只包含日期值。在 java.sql 包中存在这个类毫无意义。此外,这两个类的名称相同,这本身就是一个非常糟糕的设计。
  • 没有明确定义的类来处理时间、时间戳、格式化和解析。我们有 java.text.DateFormat 抽象类用于解析和格式化需求。通常,SimpleDateFormat 类用于解析和格式化。
  • 所有日期类都是可变的,因此它们不是线程安全的。这是 Java 日期和日历类的最大问题之一。
  • 日期类不提供国际化支持,也没有时区支持。因此引入了java.util.Calendar和java.util.TimeZone类,但它们也存在上述所有问题。

日期和日历类中定义的方法还存在一些其他问题,但上述问题清楚地表明Java需要一个强大的日期时间API。这就是为什么 Joda Time 作为Java日期时间需求的优质替代品发挥了关键作用。

Java 8日期时间设计原则

Java 8日期时间API是 JSR-310 的实现。它旨在克服传统日期时间实现中的所有缺陷。新日期时间API的一些设计原则包括:

  1. 不可变性:新日期时间API中的所有类都是不可变的,适用于多线程环境。

  2. 关注点分离:新API清楚地区分了人类可读的日期时间和机器时间(Unix时间戳)。它为日期、时间、日期时间、时间戳、时区等定义了单独的类。

  3. 清晰度: 方法清晰定义,并在所有类中执行相同的操作。例如,要获取当前实例,我们有now()方法。所有这些类中都定义了format()和parse()方法,而不是为它们单独创建一个类。

    所有类都使用工厂模式策略模式进行更好的处理。一旦您在其中一个类中使用了方法,与其他类一起使用不会很困难。

  4. 实用操作:所有新的日期时间API类都带有执行常见任务的方法,例如加、减、格式化、解析、获取日期/时间的各个部分等。

  5. 可扩展:新的日期时间API在ISO-8601日历系统上工作,但我们也可以将其与其他非ISO日历一起使用。

日期时间API包

Java 8日期时间API由以下包组成。

  1. java.time:这是新的Java日期时间API的基础包。所有主要的基础类都属于此包,例如LocalDate、LocalTime、LocalDateTime、Instant、Period、Duration等。所有这些类都是不可变的和线程安全的。大多数情况下,这些类足以满足常见需求的处理。
  2. java.time.chrono:此包定义了非ISO日历系统的通用API。我们可以扩展AbstractChronology类来创建自己的日历系统。
  3. java.time.format:此包含有用于格式化和解析日期时间对象的类。大多数情况下,我们不会直接使用它们,因为java.time包中的主要类提供了格式化和解析方法。
  4. java.time.temporal:此包含有关时间对象的临时对象,我们可以使用它来查找与日期/时间对象相关的特定日期或时间。例如,我们可以使用这些来查找月份的第一天或最后一天。您可以轻松识别这些方法,因为它们始终具有“withXXX”格式。
  5. java.time.zone Package:此包含有关支持不同时区及其规则的类。

Java 8 日期时间 API 类示例

我们已经查看了 Java 日期时间 API 的大部分重要部分。现在是时候查看带有示例的日期时间 API 的最重要类了。

1. LocalDate

LocalDate 是一个不可变类,表示具有默认格式 yyyy-MM-dd 的日期。我们可以使用 now() 方法获取当前日期。我们也可以为年、月和日提供输入参数以创建 LocalDate 实例。

该类提供了一个重载方法,用于获取当前时间的 now() 方法,我们可以传入 ZoneId 参数以获取特定时区的日期。该类提供了与 java.sql.Date 相同的功能。

package com.journaldev.java8.time;

import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;

/**
 * LocalDate 示例
 * @author pankaj
 *
 */
public class LocalDateExample {

	public static void main(String[] args) {
		
		//当前日期
		LocalDate today = LocalDate.now();
		System.out.println("Current Date="+today);
		
		//通过提供输入参数来创建 LocalDate
		LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1);
		System.out.println("Specific Date="+firstDay_2014);
		
		
		//尝试使用无效的输入创建日期
		//LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
		//异常线程 "main" java.time.DateTimeException: 
		//无效日期 'February 29',因为 '2014' 不是闰年
		
		//"Asia/Kolkata" 时区的当前日期,您可以在 ZoneId javadoc 中找到它
		LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in IST="+todayKolkata);

		//java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		//LocalDate todayIST = LocalDate.now(ZoneId.of("IST"));
		
		//从基准日期即1970年1月1日获取日期
		LocalDate dateFromBase = LocalDate.ofEpochDay(365);
		System.out.println("365th day from base date= "+dateFromBase);
		
		LocalDate hundredDay2014 = LocalDate.ofYearDay(2014, 100);
		System.out.println("100th day of 2014="+hundredDay2014);
	}

}

在注释中提供了 LocalDate 方法的解释。当我们运行这个程序时,我们会得到以下输出。

Current Date=2014-04-28
Specific Date=2014-01-01
Current Date in IST=2014-04-29
365th day from base date= 1971-01-01
100th day of 2014=2014-04-10

2. LocalTime

LocalTime是一个不可变类,其实例表示人类可读的时间格式。它的默认格式是hh:mm:ss.zzz。就像LocalDate一样,这个类提供了时区支持,并通过传入小时、分钟和秒作为输入参数来创建实例。

package com.journaldev.java8.time;

import java.time.LocalTime;
import java.time.ZoneId;

/**
 * LocalTime 示例
 * @author pankaj
 *
 */
public class LocalTimeExample {

	public static void main(String[] args) {
		
		//当前时间
		LocalTime time = LocalTime.now();
		System.out.println("Current Time="+time);
		
		//通过提供输入参数创建LocalTime
		LocalTime specificTime = LocalTime.of(12,20,25,40);
		System.out.println("Specific Time of Day="+specificTime);
		
		
		//尝试通过提供无效的输入来创建时间
		//LocalTime invalidTime = LocalTime.of(25,20);
		//Exception in thread "main" java.time.DateTimeException: 
		//HourOfDay的值无效(有效值为0-23):25
		
		//当前日期在“Asia/Kolkata”,您可以从ZoneId javadoc中获取它
		LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Time in IST="+timeKolkata);

		//java.time.zone.ZoneRulesException: 未知的时区ID:IST
		//LocalTime todayIST = LocalTime.now(ZoneId.of("IST"));
		
		//从基准日期即1970年1月1日获取日期
		LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
		System.out.println("10000th second time= "+specificSecondTime);

	}

}

输出:

Current Time=15:51:45.240
Specific Time of Day=12:20:25.000000040
Current Time in IST=04:21:45.276
10000th second time= 02:46:40

3. LocalDateTime

LocalDateTime是一个不可变的日期时间对象,表示带有默认格式yyyy-MM-dd-HH-mm-ss.zzz的日期时间。它提供了一个工厂方法,该方法接受LocalDate和LocalTime输入参数以创建LocalDateTime实例。

package com.journaldev.java8.time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;

public class LocalDateTimeExample {

	public static void main(String[] args) {
		
		//当前日期
		LocalDateTime today = LocalDateTime.now();
		System.out.println("Current DateTime="+today);
		
		//使用LocalDate和LocalTime获取当前日期
		today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
		System.out.println("Current DateTime="+today);
		
		//通过提供输入参数创建LocalDateTime
		LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
		System.out.println("Specific Date="+specificDate);
		
		
		//尝试通过提供无效输入创建日期
		//LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 25,1,1);
		//异常线程"main" java.time.DateTimeException: 
		//HourOfDay的值无效(有效值为0 - 23):25

		
		//在"Asia/Kolkata"的当前日期,您可以从ZoneId javadoc获取
		LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in IST="+todayKolkata);

		//java.time.zone.ZoneRulesException: 未知的时区ID:IST
		//LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));
		
		//从基本日期即1970年1月1日获取日期
		LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
		System.out.println("10000th second time from 01/01/1970= "+dateFromBase);

	}

}

在这三个示例中,我们看到如果为创建日期/时间提供无效参数,则会抛出java.time.DateTimeException,它是一个RuntimeException,因此我们不需要显式地捕获它。

我们还看到通过传递ZoneId可以获取日期/时间数据,您可以从其JavaDoc中获取支持的ZoneId值列表。当我们运行上述类时,我们得到以下输出。

Current DateTime=2014-04-28T16:00:49.455
Current DateTime=2014-04-28T16:00:49.493
Specific Date=2014-01-01T10:10:30
Current Date in IST=2014-04-29T04:30:49.493
10000th second time from 01/01/1970= 1970-01-01T02:46:40

4.即时

Instant类用于处理机器可读的时间格式。Instant将日期时间存储在Unix时间戳中。

package com.journaldev.java8.time;

import java.time.Duration;
import java.time.Instant;

public class InstantExample {

	public static void main(String[] args) {
		//当前时间戳
		Instant timestamp = Instant.now();
		System.out.println("Current Timestamp = "+timestamp);
		
		//从时间戳获取Instant
		Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
		System.out.println("Specific Time = "+specificTime);
		
		//持续时间示例
		Duration thirtyDay = Duration.ofDays(30);
		System.out.println(thirtyDay);
	}

}

输出:

Current Timestamp = 2014-04-28T23:20:08.489Z
Specific Time = 2014-04-28T23:20:08.489Z
PT720H

Java 8日期API实用程序

大多数日期时间主要类提供各种实用方法,如加/减天、周、月等。还有一些其他的实用方法用于使用TemporalAdjuster调整日期以及计算两个日期之间的周期。

package com.journaldev.java8.time;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.TemporalAdjusters;

public class DateAPIUtilities {

	public static void main(String[] args) {
		
		LocalDate today = LocalDate.now();
		
		//获取年份,检查是否为闰年
		System.out.println("Year "+today.getYear()+" is Leap Year? "+today.isLeapYear());
		
		//比较两个LocalDate以确定先后顺序
		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));
		
		//使用Temporal adjusters调整日期
		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);
		
		Period period = today.until(lastDayOfYear);
		System.out.println("Period Format= "+period);
		System.out.println("Months remaining in the year= "+period.getMonths());		
	}
}

输出:

Year 2014 is Leap Year? false
Today is before 01/01/2015? true
Current Time=2014-04-28T16:23:53.154
10 days after today will be 2014-05-08
3 weeks after today will be 2014-05-19
20 months after today will be 2015-12-28
10 days before today will be 2014-04-18
3 weeks before today will be 2014-04-07
20 months before today will be 2012-08-28
First date of this month= 2014-04-01
Last date of this year= 2014-12-31
Period Format= P8M3D
Months remaining in the year= 8

Java 8日期解析和格式化

将日期格式化为不同格式然后解析字符串以获取日期时间对象非常常见。

package com.journaldev.java8.time;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateParseFormatExample {

	public static void main(String[] args) {
		
		//格式化示例
		LocalDate date = LocalDate.now();
		//默认格式
		System.out.println("Default format of LocalDate="+date);
		//指定格式
		System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
		System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));
		
		
		LocalDateTime dateTime = LocalDateTime.now();
		//默认格式
		System.out.println("Default format of LocalDateTime="+dateTime);
		//指定格式
		System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
		System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
		
		Instant timestamp = Instant.now();
		//默认格式
		System.out.println("Default format of Instant="+timestamp);
		
		//解析示例
		LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
				DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
		System.out.println("Default format after parsing = "+dt);
	}

}

输出:

Default format of LocalDate=2014-04-28
28::Apr::2014
20140428
Default format of LocalDateTime=2014-04-28T16:25:49.341
28::Apr::2014 16::25::49
20140428
Default format of Instant=2014-04-28T23:25:49.342Z
Default format after parsing = 2014-04-27T21:39:48

Java 日期 API 传统日期时间支持

传统的日期/时间类几乎被所有应用程序使用,因此具有向后兼容性是必不可少的。这就是为什么有几种实用方法可以将传统类转换为新类,反之亦然。

package com.journaldev.java8.time;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class DateAPILegacySupport {

	public static void main(String[] args) {
		
		//日期转换为即时
		Instant timestamp = new Date().toInstant();
		//现在我们可以将即时转换为本地日期时间或其他类似的类
		LocalDateTime date = LocalDateTime.ofInstant(timestamp, 
						ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
		System.out.println("Date = "+date);
		
		//日历转换为即时
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);
		//时区转换为区域标识
		ZoneId defaultZone = TimeZone.getDefault().toZoneId();
		System.out.println(defaultZone);
		
		//从特定日历获取区域日期时间
		ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
		System.out.println(gregorianCalendarDateTime);
		
		//日期 API 到传统类的转换
		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 = 2014-04-28T16:28:54.340
2014-04-28T23:28:54.395Z
America/Los_Angeles
2014-04-28T16:28:54.404-07:00[America/Los_Angeles]
Mon Apr 28 16:28:54 PDT 2014
sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
java.util.GregorianCalendar[time=1398727734404,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=3,WEEK_OF_YEAR=18,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=118,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=28,SECOND=54,MILLISECOND=404,ZONE_OFFSET=-28800000,DST_OFFSET=3600000]

正如您所见,传统的TimeZoneGregorianCalendar类的toString()方法过于冗长,不够用户友好。

结论

I like this new Date Time API a lot. Some of the most used classes will be LocalDate and LocalDateTime. It’s very easy to work with the new classes. And, having similar methods that does a particular job makes it easy to find. It will take some time from moving legacy classes to new Date Time classes, but I believe it will be worth the time and effort.

Source:
https://www.digitalocean.com/community/tutorials/java-8-date-localdate-localdatetime-instant