2017-02-21 56 views
2

我正在嘗試以下列格式檢索當前日期:21-FEB-17以特定格式獲取當前日期

我有以下代碼,但它不是我需要的格式。它打印出的格式如下:21-February-17.

Format formatter = new SimpleDateFormat("dd-MMMM-yy"); 
String today = formatter.format(new Date()); 
System.out.println(today); 
+1

我會建議使用新的Java 8時間的方法。 https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html 在那裏你可以使用https://docs.oracle.com/javase/8/docs/api/ java/time/format/DateTimeFormatter.html –

回答

3

爲了得到這個月的 「前3個字母」,你應該使用

Format formatter = new SimpleDateFormat("dd-MMM-yy"); 

根據Oracle documentation of SimpleDateFormat

這將在「駱駝」情況下(即「Feb」)打印月份。如果你想在全部大寫,你需要做的

System.out.println(today.toUpperCase()); 
+0

非常感謝! – robben

2

你的格式有和額外M

Format formatter = new SimpleDateFormat("dd-MMM-yy"); 
String today = formatter.format(new Date()); 
System.out.println(today.toUpperCase()); 
+1

謝謝你,先生! – robben

2

這裏是link,以幫助您更好地瞭解。

並回答你的問題使用下面的代碼。

Format formatter = new SimpleDateFormat("dd-MMM-yy"); 
String today = formatter.format(new Date()); 
System.out.println(today.toUpperCase()); 
1

這不是你要求的答案,但它可能是你想要的答案。 :-)由於博揚佩特科維奇已經在評論已經說了,如果有什麼辦法可以使用Java 8中,您將要使用的新java.time類:

final Locale myLocale = Locale.US; 
    String today = LocalDate.now() 
      .format(DateTimeFormatter.ofPattern("d-MMM-yy", myLocale)) 
      .toUpperCase(myLocale); 
    System.out.println(today); 

此打印:

22-FEB-17 

你會注意到我爲格式化程序顯式使用了一個語言環境對象,並將其轉換爲大寫字母。你最清楚你想使用哪種語言環境。您也可以在兩個地方忽略語言環境參數,然後使用計算機的默認語言環境(這樣您將在不同的計算機上獲得不同的結果)。對於語言環境中性格式,請使用Locale.ROOT(它將更像Locale.US)。