簡體   English   中英

以特定格式顯示 Java.util.Date

[英]display Java.util.Date in a specific format

我有以下情況:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));

給出 output

Tue May 31 00:00:00 SGT 2011

但我希望 output 成為

31/05/2011 

我需要在這里使用解析,因為日期需要排序為日期而不是字符串。

有任何想法嗎??

怎么樣:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));

> 31/05/2011

您需要 go 通過SimpleDateFormat.format以便將日期格式化為字符串。

這是一個來自String -> Date -> String的示例。

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");

System.out.println(dateFormat.format(date));   // prints 31/05/2011
//                            ^^^^^^

使用 SimpleDateFormat.format

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);

您可以使用下面的代碼在 Java 中使用簡單的日期格式

SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);

這沒有任何意義,但是:

System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))

SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String

如果您想簡單地 output 一個日期,只需使用以下內容:

System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());

如此所見。 或者,如果您想將值轉換為字符串(例如,對於 SQL 建築物),您可以使用:

String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());

您還可以按照日期/時間轉換的 Java API自定義您的 output。

java.time

這是現代答案。

    DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    DateTimeFormatter displayFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.forLanguageTag("zh-SG"));

    String dateString = "31/05/2011";
    LocalDate date = LocalDate.parse(dateString, sourceFormatter);
    System.out.println(date.format(displayFormatter));

此片段中的 Output 是:

2011 年 5 月 31 日

看看你是否可以忍受兩位數的年份。 或者使用FormatStyle.MEDIUM獲取2011年5月31日 我建議您盡可能使用 Java 的內置日期和時間格式。 它更容易並且非常適合國際化。

如果您需要您提供的確切格式,也只需使用源格式化程序作為顯示格式化程序:

    System.out.println(date.format(sourceFormatter));

2011 年 5 月 31 日

我建議您不要使用SimpleDateFormat 這是出了名的麻煩和過時。 相反,我使用 java.time,即現代 Java 日期和時間 API。

要獲得特定格式,您需要將解析后的日期格式化回字符串。 老式的Date和現代的LocalDate都不能有格式。

鏈接: Oracle 教程:日期時間解釋如何使用 java.time。

你已經有了這個(這就是你輸入的) parse會將日期解析為給定格式並打印完整日期 object ( toString )。

我有這樣的事情,我的建議是使用 java 做這樣的事情,不要輸入樣板代碼

基本實現

這將對您有所幫助。 DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 打印(df.format(新日期());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM