如何在末尾没有时区的情况下将日期时间显示为当地时间?

How to display date time as local time without the timezone at the end?

编辑:由于有些看似混乱,让我澄清一下。如果可能的话,我希望解决方案在 freemarker 中完成,而不是在 java.

中完成

我有一个日期时间字符串,如下所示:2019-03-12T16:02:00+02:00 我必须以这样的特定格式显示它:EEEE dd. MMMM yyyy HH:mm 但是,如果我这样做,它会将时间显示为 14:02 而不是 16:02。 它将日期时间转换为 UTC,然后显示它。我如何让它按原样显示小时和分钟,只是最后没有 "utc" ?或者与此相关的任何时区。 Tuesday 12. March 2019 16:02 是所需的输出。

我不知道收件人的时区。

使用 iso_local_nz 给我的美国标准显示仍然是错误的。

提前致谢。

我已经尝试了这里能想到的所有方法:https://freemarker.apache.org/docs/ref_builtins_date.html#ref_builtin_date_iso

departureScheduled?datetime.iso?string("EEEE dd. MMMM yyyy HH:mmz")?capitalize

我使用的配置如下:

config = new Configuration(Configuration.VERSION_2_3_28);
config.setTemplateLoader(new S3TemplateLoader());
config.setDefaultEncoding("UTF-8");
config.setLocalizedLookup(false);
config.setLocale(Locale.forLanguageTag("NO"));
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

输入的字符串就是我上面提供的字符串。

使用 class java.time.OffsetDateTime 来处理偏移量:

public static void main(String[] args) {
    String t = "2019-03-12T16:02:00+02:00";
    OffsetDateTime odt = OffsetDateTime.parse(t);
    System.out.println(odt.format(DateTimeFormatter.ofPattern("EEEE dd. MMMM yyyy HH:mm")));
}

这会打印 Dienstag 12. März 2019 16:02,翻译取决于您的系统默认值 Locale

Note that your desired output will not be produced by correct code, because 12th March 2019 was a Tuesday and not a Monday.

到目前为止,这不是一个好的解决方案,但它适用于我遇到的一种情况,即我要显示的时间在解析之前位于原始字符串中。

departureScheduled?keep_before("+")?datetime.iso?string("EEEE dd. MMMM yyyy HH:mm")?capitalize

注意keep_before("+")

上面的解决方案通过删除 2019-03-12T16:02:00+02:00+ 之后的任何内容来实现。然后,日期时间解析器假定时间为 UTC。因此,我通过使用内置的字符串操作函数来避免整个问题,该函数 returns 不会进一步修改的子字符串:2019-03-12T16:02:00(+00:00)。括号显示了它是如何被解释的。

如果有人有更好的答案,我会将其标记为正确,但几天后,如果没有给出答案,我会将其标记为正确,以供可能遇到相同问题的任何人使用。

None 上面的答案对于实际实施很有用,所以我做了一些实验并且效果很好(在 Java 中):

ZoneId userTimezone = ZoneId.of("Europe/Rome"); // To provide as parameter
DateTimeFormatter formatter = DateTimeFormatter
    .ofPattern("dd/MM/yyyy HH:mm")
    .withZone(userTimezone);

String formattedDateTime = <any instance of ZonedDateTime>
            .format(formatter);
// OR
String formattedDateTime = <any instance of LocalDateTime> // JVM with UTC time
            .atZone(ZoneId.of("UTC")) // Adds timezone info <- Very important
            .format(formatter);       // Transforms the time at the desired zone

该字符串现在可以在该时区的用户看到的任何 template/email 中使用。

UTC Value: 20/03/2022 10:00
Output:    20/03/2022 11:00 // Without the timezone at the end