As input to Java method, I am getting date time in ISO8601 date time format and State name ( USA state name like TX, Chicago etc). I need to convert datetime to date time local to State name. For example - 2019-09-13T10:26:00-05:00 is my datetime value and get state name as Los Angeles, then I have to convert date time to Los Angeles date time. How to do it in Java? Please help
Parse your input string as a OffsetDateTime
object. The java.time classes by default parse strings in standard ISO 8601 format.
OffsetDateTime odt = OffsetDateTime.parse( "2019-09-13T10:26:00-05:00" ) ;
odt.toString(): 2019-09-13T10:26-05:00
To adjust into UTC, apply the constant for UTC.
OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC ) ;
odtUtc.toString(): 2019-09-13T15:26Z
Or extract a Instant
, as Instant
is always in UTC by definition.
Instant instant = odt.toInstant() ;
instant.toString(): 2019-09-13T15:26:00Z
Determine your time zone. A time zone is named in the format of Continent/Region
.
Naming a state, such as a state in the United States like Montana or California, is not enough. Entire states may not even be in the same time zone. You need the continent and region names as seen in the official list of time zones .
By the way "Los Angeles" is a city, not a state. But that does happen to be the name of the time zone used by much of the west coast of the United States. Well, actually, the formal time zone name is `America/Los_Angeles".
There may be a resource somewhere on the internet that maintains a mapping of cities to zones, but I do not know of any. If you expect only a certain set of cities, you could make your own mapping.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
Apply to the Instant
or OffsetDateTime
to get a ZonedDateTime
object.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2019-09-13T08:26-07:00[America/Los_Angeles]
See this code run live at IdeOne.com .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.