Skip to content Skip to sidebar Skip to footer

Android Countdown Based On Gmt/utc And Not The User's Timezone

small problem here. I have an android countdown timer that works fine, but the issue is the countdown timer will be different between users/timezone. By this I mean, for every time

Solution 1:

Use modern java.time classes rather than the troublesome old Calendar/Date classes. For Android, see the last bullets below.

Say your movie releases at 5 PM in Los Angeles time on September 23rd.

LocalDateld= LocalDate.of( 2017 , 9 , 23 ) ;
LocalTimelt= LocalTime.of( 17 , 0 ) ;

ZoneIdz= ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTimezdt= ZonedDateTime.of( ld , lt , z ) ;

Convert that to UTC, a Instant object.

Instantinstant= zdt.toInstant() ;  // Convert from a time zone to UTC. Same point on the timeline.

Calculate the time until then, as a Duration.

Durationd= Duration.between( Instant.now() , instant ) ;

Extract your number of milliseconds.

long millis = d.toMillis() ;

Perhaps you want to show the movie release date-time to a user in Québec.

ZonedIdzUser= ZoneId.of( "America/Quebec" ) ;
ZonedDateTimezdtUser= instant.atZone( zUser ) ;  // Adjust into user’s time zone. Some point on the timeline.DateTimeFormatterf= DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
Stringoutput= zdtUser.format( f ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Solution 2:

I'd recommend you to do following 2 things:

  1. Store all times in UTC, and convert it to local timezone only for UI output
  2. Synchronize time (and set it) from server side. Anyway, you can't control what time is it now at client device — it can be in wrong timezone, or have time servers off by some reason, and local time can be incorrect. Just sync time on user device with server time, store the delta if any, and show countdown based on server time.

Post a Comment for "Android Countdown Based On Gmt/utc And Not The User's Timezone"