'How to get time in current time zone from ISO 8601 strings?
In my sqlite database I have a table with a field created_at that stores time in ISO8601 as text. In the object corresponding to this table I have two fields String date, String time for the created_at attribute. Now, while querying for this table and creating a corresponding object I am stuck at converting the ISO8601 string to the current user's timezone's date (YYYY/MM/DD), time (XX:YY pm). Could anyone help me out? I thought of using substring to split the string but then the timezone is UTC for ISO8601 strings.
The ISO8601 string is stored in the database using Instant.now().toString()
tldr: created_at = ISO8601 time string; need to extract date and time portion from it for the current user.
Solution 1:[1]
Read the Wikipedia page on ISO 8601.
java.time
Capture the current moment as seen in UTC.
Instant instant = Instant.now() ;
Generate ISO 8601 string.
String output = instant.toString() ;
The Z on the end of that resulting string means an offset-from-UTC of zero hours-minutes-seconds.
Adjust into a particular time zone.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Unfortunately, the ISO 8601 standard does not define a format for a moment as seen in a time zone. The ZonedDateTime#toString method uses a format similar to ISO 8601 but appends the name of the time zone in square brackets. This is a smart solution.
String output = zdt.toString() ;
Much of your Question in not clear. I am guessing you want to pull the date and time portions from a ZonedDateTime. But I am not sure using such values to query your database makes sense. But if you insist:
LocalDate ld = zdt.toLocalDate() ;
LocalTime lt = zdt.toLocalTime() ;
You can get an ISO 8601 string for each.
String ldOutput = ld.toString() ;
String ltOutput = lt.toString() ;
Notice there is no need for the string manipulations you mentioned in your Question.
Solution 2:[2]
I think that you can see this link here you might find some answers.
But for example, you can see this example here. I have a String format and I transform it into a Date object.
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String string1 = "2001-07-04T12:08:56.235-0700";
Date result1 = df1.parse(string1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Basil Bourque |
| Solution 2 | pedro |
