Java Convert UTC to PDT/PST with Java 8 time library
My program uses LocalDateTime and the value is always in UTC.
A LocalDateTime
has no time zone at all, so it is not in UTC.
For a moment in UTC, use the Instant
class. This represents a moment on the timeline in up to nanosecond resolution.
Instant now = Instant.now();
To adjust into a time zone, apply a ZoneId
to get a ZonedDateTime
.
Never use the 3-4 letter abbreviations like PST
& PDT
so commonly seen in the mainstream media. They are not real time zones, not standardized, and are not even unique(!). Use proper time zone names in continent/region
format.
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = instant.atZone( zoneId );
It sounds like your data sink has the poor design of taking an input of a string that represents a date-time value assumed to be in America/Los_Angeles
time zone but lacking any indicator (no offset-from-UTC, no time zone).
To get such a string, lacking any offset or zone, use the predefined DateTimeFormatter
named ISO_LOCAL_DATE_TIME
. You will get a string in standard ISO 8601 format like this: 2011-12-03T10:15:30
.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME );
Your data sink omits the T
from the middle, so replace with SPACE.
output = output.replace( `T` , " " );
If your data sink expects only whole seconds, you can truncate any fractional second from your date-time value.
zdt = zdt.truncatedTo( ChronoUnit.SECONDS );
Going the other direction, from string to object, define a formatter, parse as a LocalDateTime
and apply the assumed time zone.
String input = "2011-12-03 10:15:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss" );
LocalDateTime ldt = LocalDateTime.parse( input , formatter );
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = ldt.atZone( zoneId );