Java基礎(chǔ)之LocalDateTime使用的簡(jiǎn)單總結(jié)
文章目錄
獲取當(dāng)前日期
日期比較
日期格式化
獲取當(dāng)前日期
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
//2021-03-21T14:37:45.208
日期比較
日期比較有兩種方式,第一種方式是通過(guò)compareTo方法進(jìn)行比較。如果前一個(gè)日期小于后一個(gè)日期則返回-1,如果前一個(gè)日期等于后一個(gè)日期則返回0,
如果前一個(gè)日期大于后一個(gè)日期則返回1。
//日期比較
LocalDateTime date1 = LocalDateTime.parse("2021-03-21T10:15:30");
LocalDateTime date2 = LocalDateTime.parse("2021-03-20T10:15:30");
//前一個(gè)日期小于后一個(gè)日期,則為負(fù)值,前一個(gè)日期大于后一個(gè)日期則為正值
int result = date1.compareTo(date2);
System.out.println("前一個(gè)日期大于都一個(gè)日期=" + result);
date2 = LocalDateTime.parse("2021-03-21T10:15:30");
result = date1.compareTo(date2);
System.out.println("前一個(gè)日期等于都一個(gè)日期=" + result);
date1 = LocalDateTime.parse("2021-03-20T10:15:30");
result = date1.compareTo(date2);
System.out.println("前一個(gè)日期小于都一個(gè)日期=" + result);
另外一種方式是通過(guò)isBefore方法和isAfter。對(duì)于isBefore方法,如果前一個(gè)日期小于后一個(gè)日期,則返回true,否則則返回false,即前一個(gè)日期大于或者等于后一個(gè)日期都會(huì)返回false。
LocalDate a = LocalDate.of(2021, 3, 12);
LocalDate b = LocalDate.of(2021, 3, 13);
if (a.isBefore(b)) {
System.out.println("日期A小于日期B");
}
日期格式化
LocalDateTime localDateTime = LocalDateTime.now();
// 日期格式化(格式化到年月日)
String format = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println("年月日格式化={}" + format);
String format1 = localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("年月日時(shí)分秒格式化={}" + format1);
//年月日格式化={}2021-03-21
//年月日時(shí)分秒格式化={}2021-03-21T14:44:41.038
作者:碼農(nóng)飛哥
微信公眾號(hào):碼農(nóng)飛哥