首页 > 编程语言 >Java8中LocalDateTime与时间戳timestamp的互相转换及ChronoUnit工具类

Java8中LocalDateTime与时间戳timestamp的互相转换及ChronoUnit工具类

时间:2022-10-08 18:45:39浏览次数:50  
标签:return timestamp System LocalDateTime println ChronoUnit out

Java8中LocalDateTime与时间戳timestamp的互相转换及ChronoUnit工具类

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

/**
 * Java8中LocalDateTime与时间戳timestamp的互相转换
 */
public class DateUtils {

    /**
     *
     * @param timestamp
     * @return
     */
    public static LocalDateTime timestamToDatetime(long timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     *获取指定日期的毫秒
     * @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;
    }

    public static LocalDateTime timestamToDatetimeSeconds(long timestamp){
        Instant instant = Instant.ofEpochSecond(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     * 获取指定日期的秒
     * @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;
    }

    //Date转换为LocalDateTime
    public static LocalDateTime convertDateToLDT(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    //LocalDateTime转换为Date
    public static Date convertLDTToDate(LocalDateTime time) {
        return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
    }


    //获取指定时间的指定格式
    public static String formatTime(LocalDateTime time,String pattern) {
        return time.format(DateTimeFormatter.ofPattern(pattern));
    }

    //获取当前时间的指定格式
    public static String formatNow(String pattern) {
        return formatTime(LocalDateTime.now(), pattern);
    }

    //日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
    public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
        return time.plus(number, field);
    }

    //日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
    public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field){
        return time.minus(number,field);
    }

    /**
     * 获取两个日期的差 field参数为ChronoUnit.*
     * @param startTime
     * @param endTime
     * @param field 单位(年月日时分秒)
     * @return
     */
    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
        if (field == ChronoUnit.YEARS) return period.getYears();
        if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();
        return field.between(startTime, endTime);
    }

    //获取一天的开始时间,2017,7,22 00:00
    public static LocalDateTime getDayStart(LocalDateTime time) {
        return time.withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
    }

    //获取一天的结束时间,2017,7,22 23:59:59.999999999
    public static LocalDateTime getDayEnd(LocalDateTime time) {
        return time.withHour(23)
                .withMinute(59)
                .withSecond(59)
                .withNano(999999999);
    }


    public static void main(String[] args) {
        /**
         * 1664509534345
         * ldt=2022-09-30T11:45:34.345
         * 1664509534
         * ldtSecond=2022-09-30T11:45:34
         */

        long dt = datatimeToTimestamp(LocalDateTime.now());
        System.out.println(dt);
        LocalDateTime ldt = timestamToDatetime(dt);
        System.out.println("ldt=" + ldt);

        long dtSecond = datatimeToTimestampSeconds(LocalDateTime.now());
        System.out.println(dtSecond);
        LocalDateTime ldtSecond = timestamToDatetimeSeconds(dtSecond);
        System.out.println("ldtSecond=" + ldtSecond);

        //2022年09月30日 11:52:49
        System.out.println(formatNow("yyyy年MM月dd日 HH:mm:ss"));

        /**
         * 年:1
         * 月:13
         * 日:396
         * 半日:792
         * 小时:9506
         * 分钟:570362
         * 秒:34221720
         * 毫秒:34221720000
         */
        LocalDateTime start = LocalDateTime.of(1993, 10, 13, 11, 11);
        LocalDateTime end = LocalDateTime.of(1994, 11, 13, 13, 13);
        System.out.println("年:" + betweenTwoTime(start, end, ChronoUnit.YEARS));
        System.out.println("月:" + betweenTwoTime(start, end, ChronoUnit.MONTHS));
        System.out.println("日:" + betweenTwoTime(start, end, ChronoUnit.DAYS));
        System.out.println("半日:" + betweenTwoTime(start, end, ChronoUnit.HALF_DAYS));
        System.out.println("小时:" + betweenTwoTime(start, end, ChronoUnit.HOURS));
        System.out.println("分钟:" + betweenTwoTime(start, end, ChronoUnit.MINUTES));
        System.out.println("秒:" + betweenTwoTime(start, end, ChronoUnit.SECONDS));
        System.out.println("毫秒:" + betweenTwoTime(start, end, ChronoUnit.MILLIS));

        /**
         * 2022年09月30日 12:12
         * 2024年09月30日 11:52
         */
        //增加二十分钟
        System.out.println(formatTime(plus(LocalDateTime.now(),
                20,
                ChronoUnit.MINUTES), "yyyy年MM月dd日 HH:mm"));
        //增加两年
        System.out.println(formatTime(plus(LocalDateTime.now(),
                2,
                ChronoUnit.YEARS), "yyyy年MM月dd日 HH:mm"));

        /**
         * 2022-09-30T00:00
         * 2022-09-30T23:59:59.999999999
         */
        System.out.println(getDayStart(LocalDateTime.now()));
        System.out.println(getDayEnd(LocalDateTime.now()));



        //Get the current date
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);
        //add 1 week to the current date
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("Next week: " + nextWeek);
        //add 1 month to the current date
        LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
        System.out.println("Next month: " + nextMonth);
        //add 1 year to the current date
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Next year: " + nextYear);
        //add 10 years to the current date
        LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);
        System.out.println("Date after ten year: " + nextDecade);


        /**
         * ChronoUnit====相差年-1
         * 相差{-12}月,
         * 相差天-365
         */
        //获取当前时间(2022-09-30)
        LocalDate today2 = LocalDate.now();
        //将String转LocalDateTime
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate collectTimeDate = LocalDate.parse("2023-09-30",df);
        //判断相差多少天
        System.out.println("ChronoUnit====相差年" + ChronoUnit.YEARS.between(collectTimeDate,today2));

        System.out.println(
                "相差{"+ChronoUnit.MONTHS.between(collectTimeDate,today2)+"}月," );
        ;

        System.out.println(
                "相差天"+ ChronoUnit.DAYS.between(collectTimeDate,today2));
        ;

        /**
         * ===ChronoUnit====相差年1
         * 相差{12}月,
         * 相差天365
         */

        //判断相差多少天
        System.out.println("===ChronoUnit====相差年" + ChronoUnit.YEARS.between(today2,collectTimeDate));

        System.out.println(
                "相差{"+ChronoUnit.MONTHS.between(today2,collectTimeDate)+"}月," );
        ;

        System.out.println(
                "相差天"+ ChronoUnit.DAYS.between(today2,collectTimeDate));
        ;



    }

}

 

标签:return,timestamp,System,LocalDateTime,println,ChronoUnit,out
From: https://www.cnblogs.com/oktokeep/p/16769849.html

相关文章