Java之Date Time API (Java 8 新特性)
Java 8 – Date Time API
Java 8 comes with a much improved and much required change in the way date and time is handled.
The classes that represent the date and time concepts are present in the java.time package.
The important classes in this package are:
- java.time.Period: This class represents the date part of the datetime. It represents the date part in terms of days, months and years. for example 1 year, 2 months and 5 days
- java.time.Duration: This class represents the time part of the datetime. It represents the time part in terms of seconds and nanoseconds. for example ’29 seconds’
- java.time.Instant: This represents a particular instant in the timeline. It stores the number of seconds through epoch time and also has another field that stores the nanoseconds
- java.time.LocalDate: This stores the date part of date-time in terms of years-months-days. It does not store the TimeZone. The class is immutable.
- java.time.LocalTime: This class stores the time part of date time without any TimeZone info.
- java.time.LocalDateTime: This class stores the LocalDate and LocalTime but no TimeZone
- java.time.ZonedDateTime: This class stores the LocalDateTime and the TimeZone info as a ZoneOffset object. The class has access to ZoneRules which can be used to convert to local time
- java.time.ZoneOffset:This stores the time zone offset from UTC. The zone rules are stored in ZoneId.
- java.time.OffsetDateTime:This stores the local datetime with the offset. This class does not have information about Zone Rules.
import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; /** * Java 8 – Date Time API * LocalTime:当前时间 * LocalDate:当前日期 */ @Slf4j public class LocalTimeDemo3 { // 示例1: Java 8中获取今天的日期 @Test public void test01() { LocalTime localTime = LocalTime.now(); System.out.println("当前时间:" + localTime); LocalDate localDate = LocalDate.now(); System.out.println("当前日期:" + localDate); } // 示例2:Java 8中获取年、月、日信息 @Test public void test02() { 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); } // 示例3:Java 8中处理特定日期 @Test public void test03() { LocalDate date = LocalDate.of(2018, 2, 6); System.out.println("自定义日期:" + date); } // 示例4:Java 8中判断两个日期是否相等 @Test public void test04() { LocalDate date1 = LocalDate.now(); LocalDate date2 = LocalDate.of(2018, 2, 5); if (date1.equals(date2)) { System.out.println("时间相等"); } else { System.out.println("时间不等"); } } // 示例5:Java 8中检查像生日这种周期性事件 @Test public void test05() { 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("你的生日还没有到"); } } // 示例6:Java 8中获取当前时间 @Test public void test06() { LocalTime time = LocalTime.now(); System.out.println("获取当前的时间,不含有日期:" + time); } // 示例7:Java 8中获取当前时间 @Test public void test07() { LocalTime time = LocalTime.now(); LocalTime newTime = time.plusHours(3); System.out.println("三个小时后的时间为:" + newTime); } // 示例8:Java 8如何计算一周后的日期 @Test public void test08() { LocalDate today = LocalDate.now(); System.out.println("今天的日期为:" + today); LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); System.out.println("一周后的日期为:" + nextWeek); } // 示例9:Java 8计算一年前或一年后的日期 @Test public void test09() { 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); } // 示例10:Java 8的Clock时钟类 @Test public void test10() { // 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()); } // 示例11:如何用Java判断日期是早于还是晚于另一个日期 @Test public void test11() { 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); } } // 示例16:在Java 8中获取当前的时间戳 @Test public void test16() { Instant timestamp = Instant.now(); System.out.println("What is value of this instant " + timestamp.toEpochMilli()); } // 示例17:Java 8中如何使用预定义的格式化工具去解析或格式化日期 @Test public void test17() { String dayAfterTommorrow = "20180205"; LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.println(dayAfterTommorrow + " 格式化后的日期为: " + formatted); } // 示例18:字符串互转日期类型 @Test public void test18() { 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); } /** * 获取星期几 */ @Test public void getDayOfWeek() { String s = String.valueOf(LocalDate.now().getDayOfWeek().getValue()); log.info(s); } /** * 获取当天最小时间和最大时间 */ @Test public void getDayTimeMinAndMax() { LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime min = localDateTime.with(LocalTime.MIN); LocalDateTime max = localDateTime.with(LocalTime.MAX); log.info("当天最小时间:{},当天最大时间:{}", min, max); } /** * 获取当月第一天并比较 */ @Test public void getFirstday() { LocalDate today = LocalDate.now(); LocalDate firstday = LocalDate.of(today.getYear(), today.getMonth(), 1); log.info("today:{},firstday:{}", today, firstday); int i = today.compareTo(firstday); log.info("today.compareTo(firstday):{}", i); } }
LocalDateTime
import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.net.UnknownHostException; import java.time.*; import java.time.temporal.ChronoField; /** * Java 8 – Date Time API * LocalDateTime * url:http://www.studytrails.com/java/java8/java8_date_and_time/ */ @Slf4j public class LocalDateTimeDemo2 { public static void main(String[] args) { // create a LocalDateTime LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("新建LocalDateTime对象:" + localDateTime); // prints 2018-02-12T15:08:44.116 // Convert LocalDateTime to datetime in particular zone System.out.println("指定时区:" + localDateTime.atZone(ZoneId.of("America/New_York"))); // Get the day of week from DateTime System.out.println("星期几:" + DayOfWeek.from(localDateTime)); // prints SUNDAY. // Get the day of year from DateTime System.out.println("当年第几天:" + localDateTime.get(ChronoField.DAY_OF_YEAR)); // prints 43 // The other fields that can be returned are MINUTE_OF_HOUR, MINUTE_OF_DAY, HOUR_OF_AMPM, // HOUR_OF_DAY, AMPM_OF_DAY, DAY_OF_WEEK, DAY_OF_MONTH, DAY_OF_YEAR, MONTH_OF_YEAR, // YEAR, OFFSET_SECONDS (offset from UTC). // 获得当前日期 System.out.println("当前日期:" + localDateTime.toLocalDate()); // prints 2014-09-29 // 获取当前时间 System.out.println("当前时间:" + localDateTime.toLocalTime()); // prints 22:26:30.146 // Create a LocalDateTime from year, month, day, hour, min System.out.println("实例化LocalDateTime by Int:" + LocalDateTime.of(2014, 10, 1, 10, 0)); // prints 2014-10-01T10:00 // Create LocalDateTime by parsing a string LocalDateTime parsedLocalDateTime = LocalDateTime.parse("2014-01-01T11:00"); System.out.println("实例化LocalDateTime by String:" + parsedLocalDateTime); System.out.println("当前小时点:" + localDateTime.getHour()); } /** * 时间比较 * compareTo:1大于,-1小于,0相等 */ @Test public void testCompareLocalDateTime() throws UnknownHostException { LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime2 = LocalDateTime.of(LocalDate.now(), LocalTime.of(5, 30, 00)); log.info("{}; {}", localDateTime, localDateTime2); int i = localDateTime.compareTo(localDateTime2); int i2 = localDateTime2.compareTo(localDateTime); int i3 = localDateTime2.compareTo(localDateTime2); log.info(i + "、" + i2 + "、" + i3); // 10:50:22.576 [main] INFO java8.datetime.LocalDateTimeDemo2 - 2022-04-15T10:50:22.573; 2022-04-15T05:30 // 10:50:22.582 [main] INFO java8.datetime.LocalDateTimeDemo2 - 1、-1、0 } }
Instant
1 package java8.datetime; 2 3 import java.time.Instant; 4 import java.time.temporal.ChronoUnit; 5 6 /** 7 * Java 8 – Date Time API 8 * Instant 9 * url:http://www.studytrails.com/java/java8/java8_date_and_time/ 10 */ 11 public class InstantDemo1 { 12 public static void main(String[] args) { 13 //Creating a local date 14 Instant now = Instant.now(); 15 //2018-02-12T06:29:01.493Z 16 System.out.println("当前时间:" + now); 17 18 // The epoch seconds is the number of seconds since 1970-01-01T00:00:00Z 19 System.out.println("当前秒数:" + now.getEpochSecond()); 20 21 // 调整时间 22 // the plus function allows adding time intervals. 23 // The time intervals can be NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, HALF_DAYS, DAYS 24 Instant tomorrow = now.plus(2, ChronoUnit.DAYS); 25 System.out.println("明天时间:" + tomorrow); 26 // The minus function allows subtracting time from an instant. 27 Instant yesterday = now.minus(1, ChronoUnit.DAYS); 28 System.out.println("昨天时间:" + yesterday); 29 30 // The compare function can be used to compare two dates. 31 // It returns -1 if the date that is passed is after , 1 if it is before 32 System.out.println("今天和明天比较:" + now.compareTo(tomorrow));// prints -1 33 34 // check if one instant is after another 35 System.out.println("今天是否在昨天后面:" + now.isAfter(yesterday));// prints true 36 37 } 38 }