tl;dr
You seem to want to produce a string in a certain format for the time-of-day with a zone-offset indicator.
ZonedDateTime
.now(
ZoneId.systemDefault()
)
.format(
DateTimeFormatter.ofPattern("hh:mma z")
)
Same code:
ZonedDateTime.now( ZoneId.systemDefault() ).format( DateTimeFormatter.ofPattern("hh:mma z") )
You could omit the explicit ZoneId
part, though I recommend keeping it to make clear your intentions.
ZonedDateTime.now().format( DateTimeFormatter.ofPattern("hh:mma z") )
You said:
my code is defaulting to UTC time and timezone
That means the JVM’s current default time zone was set to UTC.
Verify your actual time zone
Your code works.
I suspect your JVM has a current default time zone of UTC. Servers should generally be set to UTC as their default time zone.
Add a call to z.toString()
to verify what default zone is in play.
ZoneId z = ZoneId.systemDefault();
System.out.println( z.toString() ) ; //
Here is a slightly modified version of your code. See this code run live at IdeOne.com. Notice how we specify a time zone for the ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ; // ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern("hh:mma z") ;
String issueTime = zdt.format( f );
System.out.println( issueTime ) ;
10:25PM PST
By the way, I recommend automatically localizing rather than hard-coding a specific format. See DateTimeFormatter.ofLocalized…
methods.