Java 8 推出了全新的日期时间 API,在教程中我们将通过一些简单的实例来学习如何使用新 API。
Java处理日期、日历和时间的方式一直为社区所诟病,将 java.util.Date 设定为可变类型,以及 SimpleDateFormat 的非线程安全使其应用非常受限。
新 API 基于 ISO 标准日历系统,java.time 包下的所有类都是不可变类型而且线程安全。
编号 | 类的名称 | 描述 |
---|---|---|
1 | Instant | 时间戳 |
2 | Duration | 持续时间,时间差 |
3 | LocalDate | 只包含日期,比如:2018-02-05 |
4 | LocalTime | 只包含时间,比如:23:12:10 |
5 | LocalDateTime | 包含日期和时间,比如:2018-02-05 23:14:21 |
6 | Period | 时间段 |
7 | ZoneOffset | 时区偏移量,比如:+8:00 |
8 | ZonedDateTime | 带时区的时间 |
9 | Clock | 时钟,比如获取目前美国纽约的时间 |
10 | java.time.format.DateTimeFormatter | 时间格式化 |
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo01 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期:"+today);
}
}
/*
运行结果:
今天的日期:2018-02-05
*/
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo02 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.println("year:"+year);
System.out.println("month:"+month);
System.out.println("day:"+day);
}
}
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo03 {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2018,2,6);
System.out.println("自定义日期:"+date);
}
}
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo04 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018,2,5);
if(date1.equals(date2)){
System.out.println("时间相等");
}else{
System.out.println("时间不等");
}
}
}
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.MonthDay;
public class Demo05 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018,2,6);
MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(date1);
if(currentMonthDay.equals(birthday)){
System.out.println("是你的生日");
}else{
System.out.println("你的生日还没有到");
}
}
}
只要当天的日期和生日匹配,无论是哪一年都会打印出祝贺信息。你可以把程序整合进系统时钟,看看生日时是否会受到提醒,或者写一个单元测试来检测代码是否运行正确。
package com.shxt.demo02;
import java.time.LocalTime;
public class Demo06 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("获取当前的时间,不含有日期:"+time);
}
}
可以看到当前时间就只包含时间信息,没有日期
package com.shxt.demo02;
import java.time.LocalTime;
public class Demo07 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(3);
System.out.println("三个小时后的时间为:"+newTime);
}
}
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo08 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期为:"+today);
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("一周后的日期为:"+nextWeek);
}
}
可以看到新日期离当天日期是 7 天,也就是一周。你可以用同样的方法增加 1 个月、1 年、1 小时、1 分钟甚至一个世纪,更多选项可以查看 Java 8 API 中的 ChronoUnit 类
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo09 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println("一年前的日期 : " + previousYear);
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("一年后的日期:"+nextYear);
}
}
package com.shxt.demo02;
import java.time.Clock;
public class Demo10 {
public static void main(String[] args) {
// Returns the current time based on your system clock and set to UTC.
Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock.millis());
// Returns time based on system clock zone
Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + defaultClock.millis());
}
}
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Demo11 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate tomorrow = LocalDate.of(2018,2,6);
if(tomorrow.isAfter(today)){
System.out.println("之后的日期:"+tomorrow);
}
LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
if(yesterday.isBefore(today)){
System.out.println("之前的日期:"+yesterday);
}
}
}
package com.shxt.demo02;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo12 {
public static void main(String[] args) {
// Date and time with timezone in Java 8
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america );
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
}
}
package com.shxt.demo02;
import java.time.*;
public class Demo13 {
public static void main(String[] args) {
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}
}
package com.shxt.demo02;
import java.time.LocalDate;
public class Demo14 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
if(today.isLeapYear()){
System.out.println("This year is Leap year");
}else {
System.out.println("2018 is not a Leap year");
}
}
}
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.Period;
public class Demo15 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate java8Release = LocalDate.of(2018, 12, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : "
+ periodToNextJavaRelease.getMonths() );
}
}
package com.shxt.demo02;
import java.time.Instant;
public class Demo16 {
public static void main(String[] args) {
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp.toEpochMilli());
}
}
时间戳信息里同时包含了日期和时间,这和 java.util.Date 很像。实际上 Instant 类确实等同于 Java 8 之前的 Date 类,你可以使用 Date 类和 Instant 类各自的转换方法互相转换,例如:Date.from(Instant) 将 Instant 转换成 java.util.Date,Date.toInstant()则是将 Date 类转换成 Instant 类。
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Demo17 {
public static void main(String[] args) {
String dayAfterTommorrow = "20180205";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayAfterTommorrow+" 格式化后的日期为: "+formatted);
}
}
package com.shxt.demo02;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo18 {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
//日期转字符串
String str = date.format(format1);
System.out.println("日期转换为字符串:"+str);
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
//字符串转日期
LocalDate date2 = LocalDate.parse(str,format2);
System.out.println("日期类型:"+date2);
}
}