一、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);
}
}
输出结果文章来源:https://www.toymoban.com/news/detail-664575.html
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);
}
}
输出结果文章来源地址https://www.toymoban.com/news/detail-664575.html
nowDate is 2022-10-31T10:45:59.467
result is 2022-09-30T23:59:59
Process finished with exit code 0
到了这里,关于LocalDateTime与String日期互相转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!