问题
EDIT: Due to some seeming confusion, let me clarify. If at all possible I want the solution to be done IN freemarker and not in java.
I have a datetime string that looks like this: 2019-03-12T16:02:00+02:00
I have to show this in a specific format like this: EEEE dd. MMMM yyyy HH:mm
However, if I do it like this it shows the time as 14:02
instead of 16:02
.
It converts the datetime to UTC and then displays it. How do I make it display the hours and minutes as is, just without "utc" at the end? Or any timezone for that matter.
Tuesday 12. March 2019 16:02
is the desired output.
I do not know the timezone of the recipient.
Using iso_local_nz
gives me the american standard display which is STILL wrong.
Thank you in advance.
I have tried just about all I can think of from here: https://freemarker.apache.org/docs/ref_builtins_date.html#ref_builtin_date_iso.
departureScheduled?datetime.iso?string("EEEE dd. MMMM yyyy HH:mmz")?capitalize
The configuration I use is the following:
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);
The string being fed in is the string I provided above.
回答1:
Use the class java.time.OffsetDateTime
in order to handle the offset:
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")));
}
This prints Dienstag 12. März 2019 16:02
, translation depends on your system default Locale
.
Note that your desired output will not be produced by correct code, because 12th March 2019 was a Tuesday and not a Monday.
回答2:
This is by far not a good solution, but it works for the one case I have where the time I want to show is in the original string before it is parsed.
departureScheduled?keep_before("+")?datetime.iso?string("EEEE dd. MMMM yyyy HH:mm")?capitalize
Note the keep_before("+")
.
The solution above works by removing whatever is after the +
in 2019-03-12T16:02:00+02:00
. Then, the datetime parser assumes that the time is in UTC. Thus, I avoid the entire issue by instead using a built in string manipulation function that returns the substring that will not be modified further: 2019-03-12T16:02:00(+00:00)
. The bracket shows how it is interpreted.
If anybody has a better answer I will mark that as correct, but in a few days time, if no answer has been given, I will mark this as correct for anyone who might have the same problem.
来源:https://stackoverflow.com/questions/56985317/how-to-display-date-time-as-local-time-without-the-timezone-at-the-end