Java获取时间戳,毫秒数和秒数

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;
    }

}

 

posted on 2024-11-20 18:49  oktokeep  阅读(3)  评论(0编辑  收藏  举报