Home » Android » java – TimeFormat always from specific timezone-Exceptionshub

java – TimeFormat always from specific timezone-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have problem with date format I create App where I cant format time from current locale but always from specific locale UTC+1 or specific state, but I dont know how.

SimpleDateFormat("d.M.yyyy  HH:mm", Locale.getDefault()).format(Date(date))

i need set locale or timezone like constant which not depend on physical position or phone settings.

I have data always in UTC-0 but I need transform it to UTC+1 (or other) and show to users.

Thanks for any help

For time sync I use TrueTime library

How to&Answers:

Here is a java.time example that uses a ZonedDateTime created from a moment in time, that is an Instant in the mentioned package:

public static void main(String[] args) {
    // get a representation of a moment in time (not a specific date or time)
    Instant now = Instant.now();
    // then use that in order to represent it in a specific zone using an offset of -1 hour
    ZonedDateTime utcZdt = ZonedDateTime.ofInstant(now, ZoneOffset.ofHours(-1));
    // and use it again in order to have another one defined by a specific time zone
    ZonedDateTime laZdt = ZonedDateTime.ofInstant(now, ZoneId.of("America/Los_Angeles"));

    // and print the representation as String
    System.out.println(utcZdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println(laZdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}

The output is

2020-02-18T14:31:21.714-01:00
2020-02-18T07:31:21.714-08:00[America/Los_Angeles]

You can alternatively use an OffsetDateTime of the same package.

The key is to use an Instant, derived from epoch millis. Those millisecond values are moments in time, too, independent from zones or offsets.

You are coding an Android app, so you might have to use the ThreeTenABP, a backport of nearly the entire java.time functionality for API levels below Android 26.

I think that, nowadays, using java.time or a backport of it is the least troublesome and most straight-forward way to solve tasks like yours.

Answer:

Is this what you’re looking for?

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.M.yyyy  HH:mm");

LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, formatter);

ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC+1"));