Java獲取時間戳,毫秒數和秒數

oktokeep發表於2024-11-20

Java獲取時間戳,毫秒數和秒數

package com.example.core.mydemo.javaDemo;

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

public class TimeTest {
    public static void main(String[] args) {
        System.out.println("datatimeToTimestampSeconds = " + datatimeToTimestampSeconds(LocalDateTime.now()));
        System.out.println("datatimeToTimestamp = " + datatimeToTimestamp(LocalDateTime.now()));

    }

    /**
     * 時間戳:秒
     * @param ldt
     * @return
     */
    public static long datatimeToTimestampSeconds(LocalDateTime ldt){
//        long timestamp = ldt.toInstant(ZoneOffset.of("+8")).getEpochSecond();
//        return timestamp;

        ZoneId zone = ZoneId.systemDefault();
        long timestamp = ldt.atZone(zone).toInstant().getEpochSecond();
        return timestamp;
    }

    /**
     * 時間戳:毫秒
     * @param ldt
     * @return
     */
    public static long datatimeToTimestamp(LocalDateTime ldt){
//        long timestamp = ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();
//        return timestamp;
        ZoneId zone = ZoneId.systemDefault();
        long timestamp = ldt.atZone(zone).toInstant().toEpochMilli();
        return timestamp;
    }

}

相關文章