Java 程式將 java.util.Date 轉換為特定時區的任何本地日期


首先,設定 Date 和 ZoneId −

Date date = new Date();
ZoneId zone = ZoneId.systemDefault();

現在,將 java.util.date 轉換為 localdate −

date.toInstant().atZone(zone).toLocalDate()
date.toInstant().atZone(zone).toLocalTime()
date.toInstant().atZone(zone).getHour()
date.toInstant().atZone(zone).getMinute()
date.toInstant().atZone(zone).getSecond()

示例

import java.time.ZoneId;
import java.util.Date;
public class Demo {
   public static void main(String[] args) {
      Date date = new Date();
      ZoneId zone = ZoneId.systemDefault();
      System.out.println("LocalDate = "+date.toInstant().atZone(zone).toLocalDate());
      System.out.println("LocalTime= "+date.toInstant().atZone(zone).toLocalTime());
      System.out.println("Hour = "+date.toInstant().atZone(zone).getHour());
      System.out.println("Minute = "+date.toInstant().atZone(zone).getMinute());
      System.out.println("Seconds = "+date.toInstant().atZone(zone).getSecond());
   }
}

輸出

LocalDate = 2019-04-18
LocalTime= 23:25:09.708
Hour = 23
Minute = 25
Seconds = 9

更新於: 30-Jul-2019

162 次瀏覽

開啟 職業生涯

透過完成課程獲取認證

開始
廣告