TimeUtil.java 1.34 KB
Newer Older
刘基明's avatar
刘基明 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
package com.tanpu.community.util;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class TimeUtil {
    public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return instant.toEpochMilli();
    }

    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    //计算迄今时间
    public static String calUpToNowTime(LocalDateTime start) {
        Duration between = Duration.between(start, LocalDateTime.now());
        long duration = between.toMinutes();
        if (duration < 1) {
            return "刚刚";
        } else if (duration < 60) {
            return duration + "分钟前";
        } else if (duration < 60 * 24) {
            return duration / 60 + "小时前";
        } else if (start.getYear() == LocalDateTime.now().getYear()) {
            return start.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"));
        }
        return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}