Java 8 日期與時間筆記

網路與網站相關議題和知識
回覆文章
dtchang
Site Admin
文章: 84
註冊時間: 2017-01-22, 16:54

Java 8 日期與時間筆記

文章 dtchang » 2018-02-14, 10:06

https://www.tutorialspoint.com/java8/ja ... me_api.htm

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;


LocalDateTime currentTime = LocalDateTime.now();
目前時間, 如: 2018-02-14T09:52:14.406 (本機本地時間,己考慮時區)
LocalDate date1 = currentTime.toLocalDate();
日期,如: 2018-02-14

Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("Month: " + month +"day: " + day +"seconds: " + seconds);
結果: Month: FEBRUARYday: 14seconds: 14

LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
調整日期的月份和年份

LocalDate date32 = LocalDate.of(2018, 2 , 12);
設定為本地 2018/2/12

LocalTime date4 = LocalTime.of(22, 15);
設定時間 22:15 其他部份補 0

LocalTime date4 = LocalTime.of(22, 15,30);
設定時間 22:15:30

//字串轉時間
LocalTime date5 = LocalTime.parse("20:15:30");


import java.time.ZonedDateTime;
import java.time.ZoneId;

ZonedDateTime date1 = ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Taipei]");
//date1: 2007-12-03T10:15:30+08:00[Asia/Taipei]

ZoneId currentZone = ZoneId.systemDefault();
System.out.println("CurrentZone: " + currentZone);
//CurrentZone: Asia/Taipei

ZoneId id = ZoneId.of("Europe/Paris");
//取得指定的 ZoneId

// Date 的支援
import java.util.Date;
import java.time.Instant;
import java.time.ZoneId;

//Get the current date
Date currentDate = new Date();
System.out.println("Current date: " + currentDate);
// Current date: Wed Feb 14 12:51:41 CST 2018

//Get the instant of current date in terms of milliseconds
Instant now = currentDate.toInstant();
ZoneId currentZone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
// Local date: 2018-02-14T12:51:41.616

ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
//Zoned date: 2018-02-14T12:51:41.616+08:00[Asia/Taipei]

//Fomatter
import java.time.format.DateTimeFormatter;
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
System.out.println("Local date: " + localDateTime.format(format));
// Local date: 二月 14 2018 01:04 下午

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
System.out.println("Local date: " + localDateTime.format(format));
// Local date: 2018-02-14 01:06:34

String now2 = "2016-11-09 10:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime formatDateTime = LocalDateTime.parse(now2, formatter);
System.out.println("formatDateTime: " + formatDateTime);
// formatDateTime: 2016-11-09T10:30

回覆文章