Java處理日期吓笙、日歷和時間的方式一直為社區(qū)所詬病淑玫,將 java.util.Date設定為可變類型,以及SimpleDateFormat的非線程安全使其應用非常受限。
Java 8 推出了全新的日期時間API絮蒿,基于ISO標準日歷系統(tǒng)尊搬,java.time包下的所有類都是不可變類型而且線程安全。
1土涝、獲取當前日期和時間
1.1 獲取當前的日期佛寿,不包含時間
Java 8 中的 LocalDate 用于表示當天日期。和java.util.Date不同但壮,它只有日期冀泻,不包含時間。當你僅需要表示日期時就用這個類蜡饵。
import java.time.LocalDate;
publicclass Demo01 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期:"+today);
}
}
/*
運行結(jié)果: 今天的日期:2018-02-05
*/
1.2 獲取年弹渔、月、日信息
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);
}
}
1.3 獲取當前時間溯祸,不包含日期
當前時間就只包含時間信息肢专,沒有日期,比如:23:12:10
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("獲取當前的時間,不含有日期:"+time);
}
//獲取當前的時間,不含有日期:09:52:34.091
1.4 獲取當前的時間戳
通過Instant類獲取焦辅,Instant類有一個靜態(tài)工廠方法now()會返回當前的時間戳
import java.time.Instant;
publicclass Demo16 {
public static void main(String[] args) {
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp.toEpochMilli());
}
}
//What is value of this instant 1587866310342
2博杖、時間格式化
2.1 使用預定義的格式化工具去解析或格式化日期
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
publicclass Demo17 {
public static void main(String[] args) {
String dayAfterTommorrow = "20180205";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayAfterTommorrow+" 格式化后的日期為: "+formatted);
}
}
//20180205 格式化后的日期為: 2018-02-05
2.2 字符串互轉(zhuǎn)日期類型
LocalDateTime包含日期和時間,比如:2018-02-05 23:14:21
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
publicclass Demo18 {
public static void main(String[] args) {
//日期轉(zhuǎn)字符串
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String str = date.format(format1);
System.out.println("日期轉(zhuǎn)換為字符串:"+str);
//日期轉(zhuǎn)換為字符串:2020/04/26 10:02:36
// 字符串轉(zhuǎn)日期
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDate date2 = LocalDate.parse(str,format2);
System.out.println("日期類型:"+date2);
// 日期類型:2020-04-26
}
}
3筷登、時間加減計算
3.1 計算一周后的日期
和上個例子計算3小時以后的時間類似剃根,這個例子會計算一周后的日期。LocalDate日期不包含時間信息仆抵,它的plus()方法用來增加天跟继、周、月镣丑,ChronoUnit類聲明了這些時間單位舔糖。由于LocalDate也是不變類型,返回后一定要用變量賦值莺匠。
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
publicclass 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);
//一周后的日期為:2020-05-03
}
}
3.2 計算一年前或一年后的日期
利用minus()方法計算一年前的日期
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
publicclass 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);
}
}
//一年前的日期 : 2019-04-26
//一年后的日期:2021-04-26
3.3 獲取幾小時后時間
通過增加小時金吗、分、秒來計算將來的時間很常見趣竣。Java 8除了不變類型和線程安全的好處之外摇庙,還提供了更好的plusHours()方法替換add(),并且是兼容的遥缕。注意卫袒,這些方法返回一個全新的LocalTime實例,由于其不可變性单匣,返回后一定要用變量賦值夕凝。
import java.time.LocalTime;
publicclass Demo07 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(3);
System.out.println("三個小時后的時間為:"+newTime);
}
}
// 三個小時后的時間為:12:56:46.811
3.4 計算兩個日期之間的天數(shù)和月數(shù)——Period
有一個常見日期操作是計算兩個日期之間的天數(shù)宝穗、周數(shù)或月數(shù)。在Java 8中可以用java.time.Period類來做計算码秉。下面這個例子中逮矛,我們計算了當天和將來某一天之間的月數(shù)。
import java.time.LocalDate;
import java.time.Period;
publicclass 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() );
}
}
//Months left between today and Java 8 release : -4
4转砖、時間比較
4.1 判斷兩個日期是否相等
import java.time.LocalDate;
publicclass 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("時間不等");
}
}
}
4.2 判斷日期是早于還是晚于另一個日期
如何判斷給定的一個日期是大于某天還是小于某天须鼎?在Java 8中,LocalDate類有兩類方法isBefore()和isAfter()用于比較日期府蔗。
調(diào)用isBefore()方法時晋控,如果給定日期小于當前日期則返回true。
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
publicclass 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);
}
}
}
//之前的日期:2020-04-25
5礁竞、自定義特定日期
我們通過靜態(tài)工廠方法now()非常容易地創(chuàng)建了當天日期糖荒,你還可以調(diào)用另一個有用的工廠方法LocalDate.of()創(chuàng)建任意日期, 該方法需要傳入年模捂、月捶朵、日做參數(shù),返回對應的LocalDate實例狂男。這個方法的好處是沒再犯老API的設計錯誤综看,比如年度起始于1900,月份是從0開 始等等岖食。
import java.time.LocalDate;
publicclass Demo03 {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2018,2,6);
System.out.println("自定義日期:"+date);
}
}
6红碑、固定日期以及周期性時間
6.1 檢查像生日這種周期性事件
import java.time.LocalDate;
import java.time.MonthDay;
publicclass Demo05 {
public static void main(String[] args) {
//從生出日期獲取生日日期(只有月和日)
LocalDate date3 = LocalDate.of(2018,2,6);
MonthDay birthday = MonthDay.of(date3.getMonth(),date3.getDayOfMonth());
//獲取當前時間日期(只有月和日)
LocalDate date1 = LocalDate.now();
MonthDay currentMonthDay = MonthDay.from(date1);
if(currentMonthDay.equals(birthday)){
System.out.println("是你的生日");
}else{
System.out.println("你的生日還沒有到");
}
}
}
6.2 表示信用卡到期這類固定日期
import java.time.*;
publicclass Demo13 {
public static void main(String[] args) {
//獲取當前年月以及當前月有多少天
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
//構(gòu)建當前年月
YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
//Days in month year 2020-04: 30
//Your credit card expires on 2019-02
}
}
6.3 檢查閏年
import java.time.LocalDate;
publicclass 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");
}
}
}
7、處理時區(qū)
Java 8不僅分離了日期和時間泡垃,也把時區(qū)分離出來了∥錾海現(xiàn)在有一系列單獨的類如ZoneId來處理特定時區(qū),ZoneDateTime類來表示某時區(qū)下的時間蔑穴。這在Java 8以前都是 GregorianCalendar類來做的忠寻。
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
publicclass Demo12 {
public static void main(String[] args) {
// Date and time with timezone in Java 8
ZoneId america = ZoneId.of("America/New_York");
//通過時區(qū)構(gòu)建LocalDateTime
LocalDateTime localtDateAndTime = LocalDateTime.now(america);
System.out.println("Current date and time in a particular timezone : " + localtDateAndTime );
//Current date and time in a particular timezone : 2020-04-25T23:35:20.647
//以時區(qū)格式顯示時間
LocalDateTime ldt1 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime atZone = ldt1.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(atZone);
//2020-04-26T11:37:30.663+08:00[Asia/Shanghai]
}
}
8. Clock時鐘類
Java 8增加了一個Clock時鐘類用于獲取當時的時間戳,或當前時區(qū)下的日期時間信息存和。以前用到System.currentTimeInMillis()和TimeZone.getDefault()的地方都可用Clock替換奕剃。
import java.time.Clock;
publicclass 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());
//Clock : 1587872434146
//Clock : 1587872434146
}
}