我有 GregorianCalendar 实例,需要使用 SimpleDateFormat (或者可能与日历一起使用但提供所需的 #fromat() 功能的东西)来获得所需的输出。请建议解决方法与永久解决方案一样好。
5 回答
尝试这个:
Calendar cal = new GregorianCalendar();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.setTimeZone(cal.getTimeZone());
System.out.println(dateFormat.format(cal.getTime()));
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()));
Calendar.getTime() 返回一个可与 SimpleDateFormat 一起使用的日期。
只需调用calendar.getTime()
并将结果Date
对象传递给format
方法。
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
如果您只需要日期而不需要时间或时区,则需要进行两项更改:
- 使用
LocalDate
而不是ZonedDateTime
. - 使用
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。