LocalDateTime与String日期互相转换

一、LocalDateTime与String日期互相转换

public class Main {
    public static void main(String[] args) {
        //指定日期格式
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        //LocalDateTime转String
        String date = format.format(now);
        //String转LocalDatetime
        LocalDateTime localDate = LocalDateTime.parse(date, format);
        System.out.println("localDate is " + localDate);
    }
}

输出结果

localDate is 2022-10-31T10:28:09

Process finished with exit code 0

二、获取系统当前日期上个月的第一天

public class Main {
    public static void main(String[] args) {
        //创建当前日期
        LocalDateTime localDateTime = LocalDateTime.now();
        //获取当前日期的0时
        LocalDateTime nowDate = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), 00, 00, 00);
        //获取当前日期的第一天
        LocalDateTime firstDayOfMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("nowDate is " + nowDate);
        System.out.println("firstDayOfMonth is " + firstDayOfMonth);
    }
}

输出结果

nowDate is 2022-10-31T00:00
firstDayOfMonth is 2022-10-01T00:00

Process finished with exit code 0

三、获取系统当前日期上个月的最后一天

public class Main {
    public static void main(String[] args) {
        //获取当前日期
        LocalDateTime nowDate = LocalDateTime.now();
        //当前日期的上一个月,月份减一
        LocalDateTime localDateTime = nowDate.minusMonths(1);
        LocalDateTime lastDayOfMonth = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
        LocalDateTime result = LocalDateTime.of(lastDayOfMonth.getYear(), lastDayOfMonth.getMonthValue(), lastDayOfMonth.getDayOfMonth(), 23, 59, 59);
        System.out.println("nowDate is " + nowDate);
        System.out.println("result is " + result);
    }
}

输出结果

nowDate is 2022-10-31T10:45:59.467
result is 2022-09-30T23:59:59

Process finished with exit code 0

你可能感兴趣的:(Java,基础,java)