Android Countdown Based On Gmt/utc And Not The User's Timezone
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?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
Solution 2:
I'd recommend you to do following 2 things:
- Store all times in UTC, and convert it to local timezone only for UI output
- 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"