一、LocalDateTime與String日期互相轉(zhuǎn)換
public class Main {
public static void main(String[] args) {
//指定日期格式
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//獲取當(dāng)前日期
LocalDateTime now = LocalDateTime.now();
//LocalDateTime轉(zhuǎn)String
String date = format.format(now);
//String轉(zhuǎn)LocalDatetime
LocalDateTime localDate = LocalDateTime.parse(date, format);
System.out.println("localDate is " + localDate);
}
}
輸出結(jié)果
localDate is 2022-10-31T10:28:09
Process finished with exit code 0
二、獲取系統(tǒng)當(dāng)前日期上個(gè)月的第一天
public class Main {
public static void main(String[] args) {
//創(chuàng)建當(dāng)前日期
LocalDateTime localDateTime = LocalDateTime.now();
//獲取當(dāng)前日期的0時(shí)
LocalDateTime nowDate = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), 00, 00, 00);
//獲取當(dāng)前日期的第一天
LocalDateTime firstDayOfMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
System.out.println("nowDate is " + nowDate);
System.out.println("firstDayOfMonth is " + firstDayOfMonth);
}
}
輸出結(jié)果文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-664575.html
nowDate is 2022-10-31T00:00
firstDayOfMonth is 2022-10-01T00:00
Process finished with exit code 0
三、獲取系統(tǒng)當(dāng)前日期上個(gè)月的最后一天
public class Main {
public static void main(String[] args) {
//獲取當(dāng)前日期
LocalDateTime nowDate = LocalDateTime.now();
//當(dāng)前日期的上一個(gè)月,月份減一
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);
}
}
輸出結(jié)果文章來(lái)源地址http://www.zghlxwxcb.cn/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
到了這里,關(guān)于LocalDateTime與String日期互相轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!