Java Date、LocalDate、LocalDateTime、时间戳常见用法及转换

代码实例

		LocalDate localDate = LocalDate.now();
        //时间戳转LocalDateTime
        long currentTimeMillis = System.currentTimeMillis();
        LocalDateTime currentTimeMillisLocalDateTime = LocalDateTime.ofEpochSecond(currentTimeMillis / 1000, 0, ZoneOffset.ofHours(8));

        //Date转LocateDateTime
        LocalDateTime dateCastToLocalDateTime = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());

        //Date转LocalDate
        Date date = new Date();
        LocalDate dateCastToLocalDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();

        //LocalDateTime转Date
        Date localDateTimeCastDate = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());

        //LocalDate转Date
        ZonedDateTime zonedDateTime = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
        Date localDateCastDate = Date.from(zonedDateTime.toInstant());

        //日期格式化
        LocalDate parseDate = LocalDate.parse("2022-06-07");

        //增加一天后的日期,
        LocalDate plusDate = localDate.plus(1, ChronoUnit.DAYS);

        //减少一天后的日期
        LocalDate minusDay = localDate.minus(1, ChronoUnit.DAYS);

        //获取年
        int year = localDate.getYear();

        //获取月
        int monthValue = localDate.getMonthValue();

        //时间比较
        boolean after = plusDate.isAfter(minusDay);
        boolean before = parseDate.isBefore(minusDay);
        boolean equal = parseDate.isEqual(minusDay);

        System.out.println("currentTimeMillisLocalDateTime=" + currentTimeMillisLocalDateTime.toString());
        System.out.println("dateCastToLocalDateTime=" + dateCastToLocalDateTime.toString());
        System.out.println("dateCastToLocalDate=" + dateCastToLocalDate.toString());
        System.out.println("localDateTimeCastDate=" + localDateTimeCastDate.toString());
        System.out.println("localDateCastDate=" + localDateCastDate.toString());
        System.out.println("parseDate=" + parseDate.toString());
        System.out.println("plusDate=" + plusDate.toString());
        System.out.println("minusDay=" + minusDay.toString());
        System.out.println("year=" + year);
        System.out.println("monthValue=" + monthValue);
        System.out.println("after=" + after);
        System.out.println("before=" + before);
        System.out.println("equal=" + equal);

运行结果

currentTimeMillisLocalDateTime=2022-06-07T21:20:53
dateCastToLocalDateTime=2022-06-07T21:20:53.989
dateCastToLocalDate=2022-06-07
localDateTimeCastDate=Tue Jun 07 21:20:53 CST 2022
localDateCastDate=Tue Jun 07 00:00:00 CST 2022
parseDate=2022-06-07
plusDate=2022-06-08
minusDay=2022-06-06
year=2022
monthValue=6
after=true
before=false
equal=false

你可能感兴趣的:(开发问题,java,开发语言)