共計(jì) 651 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
要獲取指定格式的日期,可以使用 java.time 包中的 DateTimeFormatter 類(lèi)。下面是一個(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ù)需要修改日期格式。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完