How can I get UTC value in Java of any given time and date with the respective time-zone?
Say for example my current time zone is Asia/Kolkata
, now how can I get UTC value of say 1.00 am on 21/07/2018
?
How can I get UTC value in Java of any given time and date with the respective time-zone?
Say for example my current time zone is Asia/Kolkata
, now how can I get UTC value of say 1.00 am on 21/07/2018
?
For getting currect time in UTC.
Instant.now() // Current time in UTC.
For getting current time in any desired TimeZone.
ZonedDateTime.now( ZoneId.systemDefault() ) // Current time in your ZoneId.
Kolkata Example :
ZoneId zoneKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
To adjust back to UTC, extract an Instant
from the ZonedDateTime
.
Instant instant = zoneDTKolkata.toInstant() ;
You can adjust from UTC to a time zone.
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
Use the Java 8 time API instead of the older API (ie Date & SimpleDateFormat solution proposed by rajadilipkolli)
// System time (ie, your operating system time zone)
LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, minute, second);
// Time in Asia/Kolkata
ZonedDateTime kolkata = ldt.atZone(ZoneId.of("Asia/Kolkata"));
// Time in UTC
OffsetDateTime utc = ldt.atOffset(ZoneOffset.UTC);
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h.mm a 'on' dd/MM/uuuu")
.toFormatter(Locale.ENGLISH);
ZoneId zone = ZoneId.of("Asia/Kolkata");
String localDateTimeString = "1.00 am on 21/07/2018";
Instant i = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant();
System.out.println("UTC value is: " + i);
This prints:
UTC value is: 2018-07-20T19:30:00Z
I wasn’t sure whether you needed to parse the exact string you gave, 1.00 am on 21/07/2018
, into a date-time object, but in case I have shown how. The challenge is that am
is in lowercase. In order to specify case insensitive parsing I needed to go through a DateTimeFormatterBuilder
.
As you can see, the code converts to an Instant
, which is the modern way to represent a point in time in Java. Instant.toString
always prints the time in UTC. The Z
at the end means UTC. If you want a date-time that is more explicitly in UTC you may use
OffsetDateTime odt = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant()
.atOffset(ZoneOffset.UTC);
System.out.println("UTC value is: " + odt);
The output is similar, only OffsetDateTime
leaves out the seconds if they are 0 (zero):
UTC value is: 2018-07-20T19:30Z
Link: Oracle tutorial: Date Time explaining how to use java.time
, the modern Java date and time API.