70

我有 GregorianCalendar 实例,需要使用 SimpleDateFormat (或者可能与日历一起使用但提供所需的 #fromat() 功能的东西)来获得所需的输出。请建议解决方法与永久解决方案一样好。

4

5 回答 5

105

尝试这个:

Calendar cal = new GregorianCalendar();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.setTimeZone(cal.getTimeZone());
System.out.println(dateFormat.format(cal.getTime()));
于 2011-04-11T13:16:29.787 回答
39

eQui的回答少了一步

Calendar cal = new GregorianCalendar();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
#---- This uses the provided calendar for the output -----
dateFormat.setCalendar(cal); 
System.out.println(dateFormat.format(cal.getTime()));
于 2012-05-10T13:56:14.747 回答
3

Calendar.getTime() 返回一个可与 SimpleDateFormat 一起使用的日期。

于 2011-04-11T13:14:26.323 回答
3

只需调用calendar.getTime()并将结果Date对象传递给format方法。

于 2011-04-11T13:15:32.057 回答
0

java.time

我建议您使用现代 Java 日期和时间 API java.time 进行日期和时间工作。所以不是GregorianCalendar。由于 a 包含GregorianCalendar所有日期、时间和时区,因此它的一般现代替代品是ZonedDateTime.

您没有指定需要的输出是什么。我假设我们想要为人类用户输出。因此,使用 Java 内置的本地化格式作为用户的语言环境:

private static final DateTimeFormatter FORMATTER
        = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
                .withLocale(Locale.forLanguageTag("es"));

我指定西班牙语只是一个例子。如果您想使用 JVM 的默认语言环境,您可以完全指定Locale.getDefault(Locale.Category.FORMAT)或忽略调用withLocale()。现在格式化 aZonedDateTime很简单(并且比使用 a 更简单GregorianCalendar):

    ZonedDateTime zdt = ZonedDateTime.of(
            2011, 4, 11, 19, 11, 15, 0, ZoneId.of("Australia/Perth"));
    System.out.println(zdt.format(FORMATTER));

此示例的输出:

2011 年 4 月 11 日,19:11:15 AWST

如果您只需要日期而不需要时间或时区,则需要进行两项更改:

  1. 使用LocalDate而不是ZonedDateTime.
  2. 使用DateTimeFormatter.ofLocalizedDate()而不是.ofLocalizedDateTime().

如果我真的得到了GregorianCalendar怎么办?

如果您GregorianCalendar从尚未升级到 java.time 的遗留 API 获得,请转换为ZonedDateTime

    GregorianCalendar cal = new GregorianCalendar(
            TimeZone.getTimeZone(ZoneId.of("Australia/Perth")));
    cal.set(2011, Calendar.APRIL, 11, 19, 11, 15);
    ZonedDateTime zdt = cal.toZonedDateTime();

然后像以前一样继续。输出将是相同的。

关联

Oracle 教程:日期时间解释如何使用 java.time。

于 2021-12-04T13:25:13.067 回答