TimestampUtil.java 1.22 KB
package com.topdraw.util;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class TimestampUtil {

    public static Timestamp now(){
        return new Timestamp(System.currentTimeMillis());
    }

    public static Timestamp now(LocalDateTime localDateTime) {
        long epochSecond = localDateTime.toInstant(ZoneOffset.of("+8")).getEpochSecond();
        return new Timestamp(epochSecond);
    }

    public static long localDateTime2Timestamp(LocalDateTime localDateTime){
        long epochSecond = localDateTime.atZone(ZoneOffset.systemDefault()).toEpochSecond();
        return epochSecond;
    }

    public static Timestamp long2Timestamp(long timestamp){
        Timestamp timestamp1 = Timestamp.from(Instant.ofEpochSecond(timestamp));
        return timestamp1;
    }

    public static long Timestamp2long(Timestamp timestamp){
        return timestamp.toInstant().getEpochSecond();
    }

    public static void main(String[] args) {
        LocalDateTime of = LocalDateTime.of(2021, 10, 28, 11, 00, 00);
        long l = localDateTime2Timestamp(of);
        Timestamp timestamp = long2Timestamp(l);
        System.out.println(timestamp.toString());
    }
}