Convert String without ZonedId to OffsetDateTime - java

I would like to convert an String to OffsetDateTime datatype. The string has the following shape:
2017-11-27T19:06:03
I've tried two approaches:
Approach 1
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter formatter = new java.time.format.DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
return OffsetDateTime.parse(timestamp, formatter);
}
Approach 2:
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter parser = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
java.time.LocalDateTime dt = java.time.LocalDateTime.parse(timestamp, parser);
ZonedDateTime zdt = ZonedDateTime.of(dt, java.time.ZoneId.of("UTC"));
return OffsetDateTime.from(zdt);
}
First approach does not work since it complains the following:
java.time.format.DateTimeParseException: Text '2017-11-27T19:02:42' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2017-11-27T19:02:42 of type java.time.format.Parsed
For my understanding it comes from the fact that the string does not have ZoneId. How can I overwrite, on the formatter, the ZoneId so to ignore it?
The second approach comes from this question and works but it requieres 2 additional conversions, I would like to avoid those additional conversions.
Any help is going to be appreciated.

To get an OffsetDateTime from a string with no offset or time zone, you need to decide an offset or a way to get one. The most obvious way is if you know in which time zone the date-time is to be interpreted. For example:
OffsetDateTime dateTime = LocalDateTime.parse(timestamp)
.atZone(ZoneId.of("Asia/Chongqing"))
.toOffsetDateTime();
System.out.println(dateTime);
Output using the string from your question:
2017-11-27T19:06:03+08:00
Don’t be afraid of the two conversions from LocalDateTime to ZonedDateTime and then to OffsetDateTime. With java.time they are not only easy to do but also clear to read.
If you know the offset, just use that, then you need only one conversion (I am using a nonsensical offset for the example, so you will have to pick your own):
OffsetDateTime dateTime = LocalDateTime.parse(timestamp)
.atOffset(ZoneOffset.ofTotalSeconds(-36953));
System.out.println(dateTime);
Output:
2017-11-27T19:06:03-10:15:53
You may specify your desired offset as for example ZoneOffset.of("+08:00") or ZoneOffset.ofHours(8).
But to answer your question (it’s about time now).
How can I overwrite, on the formatter, the ZoneId so to ignore it?
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.parseDefaulting(ChronoField.OFFSET_SECONDS, -36953)
.toFormatter();
OffsetDateTime dateTime = OffsetDateTime.parse(timestamp, formatter);
System.out.println(dateTime);
Output is the same as the previous one (and again you will need to pick an offset that makes sense in your situation).

Finally, I've solved this issue by the following code:
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter formatter = new java.time.format.DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
return LocalDateTime.parse(timestamp, formatter)
.atOffset(java.time.ZoneOffset.UTC);
}

Related

Java 8 - Trying to parse timestamp with textual TimeZone ID

Ugh... I can't figure this out for the life of me. I'm using Java 8 and trying do to something as simple as parsing a timestamp where the TimeZone ID is a textual value such as HST:
WORKS
ZonedDateTime timestamp = ZonedDateTime.parse("2018-10-29T12:00:12.456-10:00");
DOES NOT WORK
ZonedDateTime timestamp = ZonedDateTime.parse("2018-10-29T12:00:12.456HST");
And get this error:
java.time.format.DateTimeParseException: Text '2018-10-29T12:00:12.456HST' could not be parsed at index 23
Does anyone know how to parse a timestampe where the timezone ID comes in as a textual value?
There are two problems:
1) ZonedDateTime.parse method parse only strings that obey the ISO_ZONED_DATE_TIME format, description of how it looks you can find here:
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_ZONED_DATE_TIME
In order to parse your format you have to create your own dateTimeFormatter.
This formatter can look like this
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendZoneId()
.toFormatter();
This formatter would work if you would use standart zones like GMT, UTC etc..
Problem is that HST is not standard format for Zone and is not supported. You can see supported time zones via:
System.out.println(ZoneId.getAvailableZoneIds());
If you still want to use HST zone you have to add ZoneRulesProvider for your custom zone like this:
ZoneRulesProvider.registerProvider(new ZoneRulesProvider() {
#Override
protected Set<String> provideZoneIds() {
return Collections.singleton("HST");
}
#Override
protected ZoneRules provideRules(String zoneId, boolean forCaching) {
return ZoneRules.of(ZoneOffset.ofHours(10));
}
#Override
protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
TreeMap map = new TreeMap<>();
map.put("HST",ZoneRules.of(ZoneOffset.ofHours(10)));
return map;
}
});
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendZoneId()
.toFormatter();
ZonedDateTime timestamp = ZonedDateTime.parse("2018-10-29T12:00:12.456HST", formatter);
System.out.println(timestamp);
THis should work.

Parsing date with timezone from a string

Quick (I suppose) question. How to parse string like that "2018-07-22 +3:00" to OffsetDateTime (setting time to 0:0:0.0)?
DateTimeFormatter formatter =cDateTimeFormatter.ofPattern("yyyy-MM-dd xxx");
OffsetDateTime dt = OffsetDateTime.parse("2007-07-21 +00:00", formatter);
java.time.format.DateTimeParseException: Text '2007-07-21 +00:00'
could not be parsed: Unable to obtain OffsetDateTime from
TemporalAccessor: {OffsetSeconds=0},ISO resolved to 2007-07-21 of type
java.time.format.Parsed
The trick here is to start by getting the TemporalAccessor:
TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyy-MM-dd XXX").parse("2018-07-22 +03:00");
From there, you can extract a LocalDate and a ZoneOffset:
LocalDate date = LocalDate.from(ta);
ZoneOffset tz = ZoneOffset.from(ta);
And combine them like so:
ZonedDateTime zdt = date.atStartOfDay(tz);
An OffsetDateTime requires a time-of-day, but your format string doesn't supply that, so you need to tell the DateTimeFormatter to default time-of-day to midnight.
Also, offset +3:00 is invalid, since hour must be 2-digit, which means you need to fix that first.
This will do both:
public static OffsetDateTime parse(String text) {
// Fix 1-digit offset hour
String s = text.replaceFirst("( [+-])(\\d:\\d\\d)$", "$10$2");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd xxx")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
return OffsetDateTime.parse(s, formatter);
}
Test
System.out.println(parse("2018-07-22 +3:00"));
System.out.println(parse("2018-07-22 +03:00"));
System.out.println(parse("2007-07-21 +00:00"));
Output
2018-07-22T00:00+03:00
2018-07-22T00:00+03:00
2007-07-21T00:00Z

UnsupportedTemporalTypeException: Unsupported field: InstantSeconds

I have this code which is producing a timestamp and then parsing.
DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern("yyyyMMdd kk:HH:ss.SSSZ")
.withLocale(Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant now = Instant.now();
String formatted = formatter.format(now);
Instant parsed = formatter.parse(formatted, Instant::from);
When it runs, the last line produces an exception:
java.time.format.DateTimeParseException: Text '20180123 12:12:45.648-0500' could not be parsed: Unable to obtain Instant from TemporalAccessor: {SecondOfMinute=45, NanoOfSecond=648000000, OffsetSeconds=-18000, MilliOfSecond=648, MicroOfSecond=648000, HourOfDay=12},ISO,America/New_York resolved to 2018-01-23 of type java.time.format.Parsed
Caused by: java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {SecondOfMinute=45, NanoOfSecond=648000000, OffsetSeconds=-18000, MilliOfSecond=648, MicroOfSecond=648000, HourOfDay=12},ISO,America/New_York resolved to 2018-01-23 of type java.time.format.Parsed
Caused by: java.time.temporal.UnsupportedTemporalTypeException: **Unsupported field: InstantSeconds**
I replace the formatter with DateTimeFormatter.ISO_INSTANT, it works correctly. The actual data produced are nearly identical. What is the disconnect?
ISO_INSTANT: 2018-01-23T16:51:25.516Z
My Format: 20180119 23:59:59.999-0800
I am required to use my format. What is the problem here?
The problem is that your format does not completely represent an Instant because your format does not have a representation for minutes at all. The formatter can correctly go from Instant and output the result in your format because an Instant has all of the data that your format requires, but your format does not have everything that an Instant requires.
Try changing your pattern to yyyyMMdd kk:HH:mm:ss.SSS, and you will see that your code now works. Note the addition of mm.
If you absolutely require a minuteless pattern, you should make your own TemporalQuery to extract the information you require from the TemporalAccessor
In this case, I simply set minutes to 0:
public class MyQuery implements TemporalQuery<Instant> {
#Override
public Instant queryFrom(TemporalAccessor temporal) {
LocalDate ld = LocalDate.from(temporal);
LocalTime lt = LocalTime.of(temporal.get(ChronoField.HOUR_OF_DAY), 0, temporal.get(ChronoField.SECOND_OF_MINUTE), temporal.get(ChronoField.NANO_OF_SECOND));
return ZonedDateTime.of(ld, lt, ZoneId.systemDefault()).toInstant();
}
}
We can then use this TemporalQuery like this:
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyyMMdd kk:HH:mm:ss.SSS")
.withLocale(Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant now = Instant.now();
String formatted = formatter.format(now);
System.out.println(formatted);
Instant ld = formatter.parse(formatted, new MyQuery());
}
}
I know that this is an old question but if you're looking for a short answer just add a locale and zone to the DateTimeFormatter, you may also use the default ones: .withLocale(Locale.getDefault()).withZone(ZoneId.systemDefault())
Here is an example of code:
Instant now = Instant.now();
System.out.println(now.toString());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").withLocale(Locale.getDefault()).withZone(ZoneId.systemDefault());
System.out.println(formatter.format(now));
This code will use the current instant, output the sample, format it with the date time formatter and output the formatted instant.

Parse datetime without offset in OffsetDateTime java

Can I somehow parse a datetime that's without offset using OffsetDateTime.parse(....)
Java code:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS XXX");
OffsetDateTime date = OffsetDateTime.parse("2017-02-03 12:30:3000", FORMATTER);
I'm getting datetime as a String without offset, but need to parse it into OffsetDateTime, I know I need an offset here, but can I some how alter that String to insert default/dummy offset (maybe +00:00) & parse it using OffsetDateTime. The problem is that object has to be OffsetDateTime.
The simplest solution is to parse your string into a LocalDateTime and then convert:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
OffsetDateTime date = LocalDateTime.parse("2017-02-03 12:30:30", formatter)
.atOffset(ZoneOffset.UTC);
This gives an OffsetDateTime of 2017-02-03T12:30:30Z, where Z means UTC or offset zero.
You can parse directly into an OffsetDateTime if you want:
DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
OffsetDateTime date = OffsetDateTime.parse("2017-02-03 12:30:30", FORMATTER);
Finally, if you are required to use the formatter given in the question, altering the string to fit is of course an option. For example:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS XXX");
String fixedDateTimeString
= "2017-02-03 12:30:3000".replaceFirst("(\\d{2})0*$", "$1.000 +00:00");
OffsetDateTime date = OffsetDateTime.parse(fixedDateTimeString, FORMATTER);
As you can see, in the last example I have also kept the too many zeroes in the string I am using as a starting point, removing them in the same operation that appends the offset. The result is the same, 2017-02-03T12:30:30Z.
Edit: uuuu or yyyy for year in the format pattern string? Since the year is always in the common era (Anno Domini), either works. yyyy is for year of era and would be right of there was an era designator (like AD or BC, format pattern letter G). uuuu is a signed year, where year 0 means 1 BCE, -1 means 2 BCE, etc. There’s more in this question: uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Actually I achieved it by:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
OffsetDateTime.of(LocalDateTime.parse("2017-02-03 12:30:30", FORMATTER), ZoneOffset.UTC);

java 8 getting string value for current date with offset

I want to the get the current date in this format "2017-09-07T11:55:32+00:00"
but not overly familar with how to do it in Java 8.. have tried
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
String todaysDateTime = now.format(formatter);
gives me an error
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field:
OffsetSeconds
anyone know i how i do this?
OffsetDateTime odt = now.atOffset(ZoneOffset.ofHoursMinutes(1, 0));
System.out.println(odt);
The toString of all time variants already give the corresponding ISO format.
2017-11-08T15:31:04.115+01:00
However instead of +00:00 it will give Z. Also the milliseconds are given. So either use this standard, or make your own pattern.
Your format would be:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx");
where the small x (instead of X) does no "Z" substitution, and xxx is needed for the colon :.
So the resulting string can be gotten as (thanks #OleV.V.):
OffsetDateTime.now(ZoneOffset.UTC)
.format(DateTimeFormatter.‌​ofPattern("yyyy-MM-d‌​d'T'HH:mm:ssxxx"))
The other direction:
LocalDateTime wraps a long, a milliseconds since - count. It no longer holds the offset as in OffsetDateTime.
OffsetDateTime odt = fmt.parse(inputString);
Instant instant = odt.toInstant(); // Bare bone UTC time.
LocalDateTime ldt = LocalDateTime.ofInstant(odt.toInstant(), ZoneId.of("UTC")); // UTC too.
(This is a bit more complicated than I thought.)

Categories