简体   繁体   中英

Alfresco : Format date to current time zone

Let's say I have a Java "Date" object. I would like to convert/format it to the current time zone of my Spring Boot/Alfresco service application.

How can I achieve this? I know Alfresco does it to display the date in formularies.

For example, I have a date property set to 3 pm (UTC), the system will display "17:00:00" (5pm, french time).

I would like to get the same result but with Java.

Any idea?

Thank you!

If you could use java.time (Java 8+ needed), you could get the default zone id of a system with

ZoneId sysDefault = ZoneId.systemDefault();

You can get the current time with the speaking method now() , in this case use a ZonedDateTime.now() for the time in the system default zone or apply a zone to now(ZoneId) if you want the current time in a specific zone.

Having a zone and/or a ZonedDateTime , you can safely switch between zones, the conversion will be handled by the class(es). You can use DateTimeFormatter s in order to alter display styles, like 24h or 12h format, double-digit units or single-digit ones and so on.

Here's a simple example for switching a datetime from UTC to Paris zone. The zones in this example are fixed, but you can use the system default zone id of your server instead of the Paris zone.

public static void main(String[] args) {
    // define the zones needed for conversion, one for UTC
    ZoneId utc = ZoneId.of("UTC");
    // and a second one for Paris
    ZoneId paris = ZoneId.of("Europe/Paris");
    // create date and time of day in utc
    ZonedDateTime threePmUtc = ZonedDateTime.of(2022, 8, 5, 15, 0, 0, 0, utc);
    // display its time of day once
    System.out.println(threePmUtc.toLocalTime()
                                 .format(DateTimeFormatter.ISO_LOCAL_TIME));
    // then convert to Paris time
    ZonedDateTime fivePmParis = threePmUtc.withZoneSameInstant(paris);
    // display its time of day
    System.out.println(fivePmParis.toLocalTime()
                                  .format(DateTimeFormatter.ISO_LOCAL_TIME));
    /*
     * if you want more control over the output,
     * e.g. don't print seconds if they are zero or switch to 12h format,
     * then build a formatter with your desired format
     */
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h.mm a", Locale.ENGLISH);
    // and print the formatted value
    System.out.println(fivePmParis.toLocalTime()
                                  .format(dtf));
}

Output:

15:00:00
17:00:00
5.00 PM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM