以特定格式获取当前日期

时间:2017-02-21 21:13:34

标签: java

我正在尝试按以下格式检索当前日期:21-February-17.

我有以下代码,但它不是我需要的格式。它以下列格式打印出来:Format formatter = new SimpleDateFormat("dd-MMMM-yy"); String today = formatter.format(new Date()); System.out.println(today);

{{1}}

4 个答案:

答案 0 :(得分:3)

要获得当月的“前3个字母”,您应该使用

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

根据Oracle documentation of SimpleDateFormat

那将在“骆驼”案例中打印月份(即“2月”)。如果你想要全部大写,你需要做

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

答案 1 :(得分:2)

您的格式有额外的M

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

答案 2 :(得分:2)

以下link可帮助您更好地理解。

要回答您的问题,请使用以下代码。

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

答案 3 :(得分:1)

这不是您要求的答案,但它可能是您想要的答案。 :-)正如Bojan Petkovic在评论中已经说过,如果有任何方法可以使用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参数,然后将使用计算机的默认语言环境(因此您将在不同的计算机上获得不同的结果)。对于区域设置中性格式,请使用Locale.ROOT(它将更像Locale.US)。

相关问题