Skip to content

Instantly share code, notes, and snippets.

@sshark
Created June 23, 2021 03:05
Show Gist options
  • Select an option

  • Save sshark/5dab61c9facaecf964bd3f9d8e2a97bf to your computer and use it in GitHub Desktop.

Select an option

Save sshark/5dab61c9facaecf964bd3f9d8e2a97bf to your computer and use it in GitHub Desktop.
Getting the right UTC at the targeted time zone
/*
* Setting the right time for the targeted zone e.g. Asia/Singapore
* LocalDateTime.now(ZoneId.of("Asia/Singapore")) // set the time of the targeted time zone
* .atZone(ZoneId.of("Asia/Singapore")) // set the time zone ONLY for the time above. Doesn't affect time
* .toEpochSecond() // find the UTC time for the time at the timezone and convert it to seconds
*/
System.out.println(LocalDateTime.now(ZoneId.of("Asia/Singapore")).atZone(ZoneId.of("Asia/Singapore")).toEpochSecond());
/*
* Shorter versions with ZonedDateTime
*/
System.out.println(ZonedDateTime.now(ZoneId.of("Asia/Singapore")).toEpochSecond());
// Target time zone is Calcutta
System.out.println(ZonedDateTime.now(ZoneId.of("Asia/Calcutta")).toEpochSecond());
// All should show the same UTC seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment