How to get current time in another TimeZone in Java?

OK - I feel pretty dumb asking such a basic question, but hey.

I am trying to get the current time in a different time zone in Java webapp. I tried the following obvious solution: in my servlet

Calendar localCalendar = Calendar.getInstance(myBean.getTimeZone());

then I pass the calendar object through the JSP as the request attribute "localCalendar":

It is now: [${requestScope.localCalendar.time}]
in TimeZone ${requestScope.localCalendar.timeZone.ID}

but my conclusion seems to ignore the set of time zones, i.e.

It is now: [Thu Nov 26 10:01:03 GMT 2009] in TimeZone Indian/Mahe

I assume this has something to do with the Locale settings, is there a way to get the time formatted for my Locale in a different time zone?

+1
source share
3 answers

Internal data Calendaris mainly:

, Epoch, 1 1970 . 00: 00: 00.000 GMT (-).

, long, , , , toString promises.

. (JSP), , JSTL, bean, DateFormat .

+6
+3

McDowell , java.util.Calendar ( java.util.Date) .

java.time

java.time Java 8 Java 6 7 Android. , , .

An Instant - UTC.

Instant now = Instant.now();

ZoneId, ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

, Locale . , UTC. Locale . () () , , ..

For example, you might have a French Québécois reader who accesses your page while working in India . Therefore, use the time zone Asia/Kolkatac Locale.CANADA_FRENCH.

To generate a formatted string, use the class DateTimeFormatter. Many examples already exist in Stack Overflow. Indicate what you want / expect Localeusing the method withLocale.

0
source

Source: https://habr.com/ru/post/1724175/


All Articles