2017年9月16日 星期六

Java 8 的 Date 及 Time 的處理

方便機器處理的日期時間類別 java.time.Instant; java.time.Duration.

方便人類閱讀的日期時間類別: java.time.LocalDate, java.time.LocalTime, java.time.LocalDateTime; java.time.Period
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaplayground;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
/**
*
* @author user
*/
public class JavaPlayground {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Time for machine to read
Instant t = Instant.ofEpochSecond(3);
System.out.println("Unix epoch time passing 3 seconds: " + t);
Instant now = Instant.now();
System.out.println("Now:" + now);
// Duration is the time for machine to read
// Store the number of seconds or nanosecond from the unix epoch (1770-01-01T00:00:00)
LocalDateTime d1 = LocalDateTime.of(2017, 9, 17, 0, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 9, 20, 0, 0);
System.out.println("Duration: " + Duration.between(d1, d2).getSeconds() + "Seconds");
// Period is the time for human to read
// Handle amount of time in terms of years, months, and days
LocalDate d3 = LocalDate.of(2017, 9, 17);
LocalDate d4 = LocalDate.of(2018, 9, 20);
System.out.println("Period:" + Period.between(d3, d4));
}
}