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

编辑:由于有些看似混乱,让我澄清一下。如果可能的话,我希望解决方案在 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);

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


温温酱
浏览 139回答 3
3回答

catspeake

到目前为止,这不是一个好的解决方案,但它适用于我遇到的一种情况,即我要显示的时间在解析之前位于原始字符串中。departureScheduled?keep_before("+")?datetime.iso?string("EEEE dd. MMMM yyyy HH:mm")?capitalize注意keep_before("+").+上面的解决方案通过删除in之后的任何内容来工作2019-03-12T16:02:00+02:00。然后,日期时间解析器假定时间为 UTC。因此,我通过使用一个内置的字符串操作函数来避免整个问题,该函数返回不会被进一步修改的子字符串:2019-03-12T16:02:00(+00:00)。括号显示了它是如何被解释的。如果有人有更好的答案,我会将其标记为正确,但几天后,如果没有给出答案,我会将其标记为正确,以供可能遇到相同问题的任何人使用。

绝地无双

使用该类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。请注意,正确的代码不会产生您想要的输出,因为 2019 年 3 月 12 日是星期二而不是星期一。

慕哥6287543

上面的答案都不适用于实际实现,所以我做了一些实验,这很完美(在 Java 中):ZoneId userTimezone = ZoneId.of("Europe/Rome"); // To provide as parameterDateTimeFormatter formatter = DateTimeFormatter&nbsp; &nbsp; .ofPattern("dd/MM/yyyy HH:mm")&nbsp; &nbsp; .withZone(userTimezone);String formattedDateTime = <any instance of ZonedDateTime>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .format(formatter);// ORString formattedDateTime = <any instance of LocalDateTime> // JVM with UTC time&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .atZone(ZoneId.of("UTC")) // Adds timezone info <- Very important&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .format(formatter);&nbsp; &nbsp; &nbsp; &nbsp;// Transforms the time at the desired zone该字符串现在可用于该时区用户将看到的任何模板/电子邮件。UTC Value: 20/03/2022 10:00Output:&nbsp; &nbsp; 20/03/2022 11:00 // Without the timezone at the end
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java