java8新特性之日期時間
LocalDate類使用ISO日曆表示年、月、日。 常用方法: 1、LocalDate.now():獲取系統當前日期。 2、LocalDate.of(int year,int month,int dayOfMonth) 按指定日期建立LocalDate物件。 3、getYear():返回日期當中的年份。 4、getMonth():返回日期中的月份。 5、getDayOfMonth():返回月份中的日。 LocalTime類的常用方法: 1、LocalTime.now():獲取系統當前時間。 2、LocalTime.of(int hour,int minute,int second) 按指定時間建立LocalTime物件。 3、getHour():返回小時 4、getMinute():返回分鐘 5、getSecond():返回秒
LocalDateTime類用於表示日期和時間 常用方法: 1、LocalDateTime.now():獲取系統當前時間。 2、LocalDateTime.of(int year,int month,int dayOfMonth,int hour,int minute,int second) 按指定日期和時間建立LocalDateTime物件。 getYear():返回日期當中的年份。 getMonth():返回日期中的月份。 getDayOfMonth():返回月份中的日。 getHour():返回小時 getMinute():返回分鐘 getSecond():返回秒
DateTimeFormatter類用於將字串解析為日期 常用方法: 1、static ofPattern(String pattern); 作用:按pattern字串指定的格式建立DateTimeFormatter物件 2、LocalDateTime.parse(strDate,formatter);
ZonedDateTime類 ZonedDateTime處理日期和時間與相應的時區。 1、ZonedDateTime.now() 獲取系統當前日期和時間 2、String format(DateTimeFormatter formatter)。 按指定模板將日期物件格式化為一個字串。
測試案例:
package com.jk.streamtest;
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter;
public class Test06_LocalDate {
public static void main(String[] args) { LocalDate date = LocalDate.now(); System.out.print(date.getYear()+"年"); System.out.print(date.getMonthValue()+"月"); System.out.println(date.getDayOfMonth()+"日"); System.out.println(date.toString()); getTime(); getLocalDateTime(); getTimeFormatter(); testzonedDateTime(); } public static void getTime() { LocalTime time = LocalTime.now(); System.out.print(time.getHour()+"時"); System.out.print(time.getMinute()+"分"); System.out.println(time.getSecond()+"秒"); System.out.println(time.toString()); } public static void getLocalDateTime() { LocalDateTime ltime = LocalDateTime.now(); System.out.println("========================================"); System.out.print(ltime.getYear()+"年"); System.out.print(ltime.getMonthValue()+"月"); System.out.println(ltime.getDayOfMonth()+"日"); System.out.print(ltime.getHour()+"時"); System.out.print(ltime.getMinute()+"分"); System.out.println(ltime.getSecond()+"秒"); System.out.println(ltime.toString()); } public static void getTimeFormatter() { DateTimeFormatter dm = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss"); LocalDateTime date = LocalDateTime.parse("2014-04-01:13:24:01",dm); System.out.println(date.toString()); } public static void testzonedDateTime() { ZonedDateTime date = ZonedDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy:HH:mm:ss"); String strDate = date.format(formatter); System.out.println("======================================="); System.out.println(strDate); } }