網頁

2020/5/21

Java 取得系統當日午夜毫秒時間 get system current day midnight millisecond

Java LocalDateTiem取得系統所在時區當天及昨天午夜(00:00)的毫秒。

方法一,取得當日期昨天的LocalDate後將時間設為00:00。

import java.time.LocalDate;
import java.time.ZoneId;

public class Main {

    public static void main(String[] args) {

        // 本篇撰寫於Taiwan 2020-05-23 (時區為"Asia/Taipei")
        long todayMidnightMillis = getTodayMidnightMillis();
        long yesterdayMidnightMillis = getYesterdayMidnightMillis();

        System.out.println(todayMidnightMillis); // 1590163200000  (Sat May 23 2020 00:00:00) 本日00:00
        System.out.println(yesterdayMidnightMillis); // 1590076800000 (Fri May 22 2020 00:00:00) 昨日00:00

    }

    private static long getTodayMidnightMillis() {
        LocalDate d = LocalDate.now();
        return toMidnightMillis(d);
    }

    private static long getYesterdayMidnightMillis() {
        LocalDate d = LocalDate.now().minusDays(1L);
        return toMidnightMillis(d);
    }

    private static long toMidnightMillis(LocalDate d) {
        return d.atTime(
                0, // hour
                0, // minute
                0 // second
        ).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }
    
}

方法二,取得當日及昨日的LocalDatTime後將時間部分改為00:00。

package com.abc.demo;

import java.time.LocalDateTime;
import java.time.ZoneId;

public class Main {

    public static void main(String[] args) {

        // 本篇撰寫於Taiwan 2020-05-21 (時區為"Asia/Taipei")
        long todayMidnightMillis = getTodayMidnightMillis();
        long yesterdayMidnightMillis = getYesterdayMidnightMillis();

        System.out.println(todayMidnightMillis); // 1589990400000  (Thu May 21 2020 00:00:00) 本日00:00
        System.out.println(yesterdayMidnightMillis); // 1589904000000 (Wed May 20 2020 00:00:00) 昨日00:00

    }

    private static long getTodayMidnightMillis() {
        LocalDateTime d = LocalDateTime.now();
        return toMidnightMillis(d);
    }

    private static long getYesterdayMidnightMillis() {
        LocalDateTime d = LocalDateTime.now().minusDays(1L);
        return toMidnightMillis(d);
    }

    private static long toMidnightMillis(LocalDateTime d) {
        return LocalDateTime.of(
                d.getYear(),
                d.getMonthValue(),
                d.getDayOfMonth(),
                0, // hour
                0, // minute
                0 // second
        ).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

}

沒有留言:

張貼留言