一、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
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐