java怎么獲取指定格式日期

小億
123
2023-10-12 19:01:25

要獲取指定格式的日期,可以使用java.time包中的DateTimeFormatter類。下面是一個(gè)示例代碼,演示如何獲取指定格式的日期:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 獲取當(dāng)前日期
LocalDate currentDate = LocalDate.now();
// 創(chuàng)建一個(gè)日期格式化器,指定要獲取的日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 使用日期格式化器將日期轉(zhuǎn)換為指定格式的字符串
String formattedDate = currentDate.format(formatter);
// 輸出結(jié)果
System.out.println("Formatted Date: " + formattedDate);
}
}

在上面的代碼中,我們首先獲取當(dāng)前日期LocalDate.now(),然后創(chuàng)建一個(gè)日期格式化器DateTimeFormatter,并使用ofPattern方法指定要獲取的日期格式。最后,使用format方法將日期轉(zhuǎn)換為指定格式的字符串。輸出結(jié)果將顯示格式化后的日期。

在這個(gè)示例中,我們將日期格式指定為"yyyy-MM-dd",你可以根據(jù)需要修改日期格式。

0