Parse String timestamp to Instant throws Unsupported field: InstantSeconds - java

I am trying to convert a String into an Instant. Can you help me out?
I get following exception:
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
at java.time.format.Parsed.getLong(Parsed.java:203)
at java.time.Instant.from(Instant.java:373)
My code looks basically like this
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
Instant result = Instant.from(temporalAccessor);
I am using Java 8 Update 72.

A simpler method is to add the default timezone to the formatter object when declaring it
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
Instant result = Instant.from(formatter.parse(timestamp));

Here is how to get an Instant with a default time zone. Your String can not be parsed straight to Instant because timezone is missing. So you can always get the default one
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
Instant result = Instant.from(zonedDateTime);

I wrote such simple function to perform the conversion:
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.ZonedDateTime;
import java.time.Instant;
import java.sql.Timestamp;
public class SqlTimestampParser {
public static Timestamp parseTimestamp(String dateTime, String format) throws Exception {
if (format == null || format.trim().length() == 0) {
throw new Exception("No format defined!");
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
ZonedDateTime timed = ZonedDateTime.parse(dateTime, formatter);
timed.format(formatter);
Instant x = Instant.from(timed);
return Timestamp.from(x);
}
}
With sample usage:
SqlTimestampParser.parseTimestamp('2020-09-17 16:20:35.294000+00:00',"yyyy-MM-dd HH:mm:ss.SSSSSSXXX")

First convert your date into util date using date format as you don't have time zone in your input. Then you can convert that date into Instant date. This will give you date with accurate time.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
Date xmlDate = dateFormat.parse(timestamp);
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Instant instantXmlDate = Instant.parse(dateFormat.format(xmlDate));

Related

Trying to convert from 2023-01-11 18:27:59UTC-06:00 to 2023-01-12T00:27:59.000Z -- parsing fails

I have string date format like below
2023-01-11 18:27:59UTC-06:00
need to convert to like 2023-01-12T00:27:59.000Z (in UTC zone)
I tried the below. I am getting exception Exception in thread "main" java.time.format.DateTimeParseException: Text '2023-01-09 23:56:59UTC-05:30' could not be parsed at index 10. The exception is coming from this line:
LocalDateTime labelTime = LocalDateTime.parse(dateUTC, DateTimeFormatter.ofPattern(INPUT_FORMAT));
My short code example:
String dateUTC="2023-01-09 23:56:59UTC-05:30";
final String INPUT_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
final String OUTPUT_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX";
final DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(OUTPUT_FORMAT);
LocalDateTime labelTime = LocalDateTime.parse(dateUTC, DateTimeFormatter.ofPattern(INPUT_FORMAT));
ZoneId utcZoneId = ZoneId.of("UTC");
ZonedDateTime zdt = labelTime.atZone(utcZoneId);
System.out.println("OUT PUT Format"+dtf2.format(zdt));
Use the pattern, uuuu-MM-dd HH:mm:ss'UTC'XXX to parse the given date-time string into an OffsetDateTime and convert the result into another OffsetDateTime with ZoneOffset.UTC using OffsetDateTime#withOffsetSameInstant.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss'UTC'XXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2023-01-11 18:27:59UTC-06:00", parser)
.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odt);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
String formatted = odt.format(formatter);
System.out.println(formatted);
}
}
Output:
2023-01-12T00:27:59Z
2023-01-12T00:27:59.000Z
ONLINE DEMO
Note: Here, you can use y instead of u but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.

Can't get LocalDate to Parse correctly

String date = "08/02/2022 Tuesday";
DateTimeFormatter LONG_DATE_FORMAT_ddMMyyyyEEEE = ofPattern("dd/MM/yyyy EEEE");
LocalDate.parse(date, LONG_DATE_FORMAT_ddMMyyyyEEEE);
I'm getting a DateTimeParseException with the following message: Text 08/02/2022 Tuesday' could not be parsed at index 11.
I suppose this is an issue with the EEEE side of my format, but I can't seem to understand what should replace it.
This is java 1.8.0_311
We need DateTimeFormatter class to format date string properly. We also need to convert the string date to LocalDate object and back to string again to display. The DateTimeParseException class handles any undesired outcomes.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class Main {
public static void main(String[] args) {
try{
String date = "08-02-2022 Tuesday";
DateTimeFormatter pattern =
DateTimeFormatter.ofPattern("dd-MM-yyyy eeee");
// parsing string date to LocalDate obj
// The part you were missing
LocalDate formattedDate = LocalDate.parse(date, pattern);
// Again converting to string
System.out.println(formattedDate.format(pattern));
}
// handling exception for unparseble dates
catch(DateTimeParseException x){
System.out.println("The given date cannot be parsed");
}
}
}
LocalDate contains of a day, month, and year (Variation between +999999999-12-31 and -999999999-12-31)
Things like time and other values are rejected by the parsing. If you would like the day of the week, you can use a function like:
// Parses the date
LocalDate dt = LocalDate.parse("2018-11-27");
// Prints the day
System.out.println(dt.getDayOfWeek());
This works for me:
String date = "08/02/2022 Tuesday";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy EEEE");
LocalDate time = LocalDate.parse(date, formatter);
System.out.println(time.format(formatter));

2020-04-03 20:17:46 to "yyyy-MM-dd'T'HH:mm:ss" format

Is there any way in java(java.util.* or Joda api ) to convert "2020-04-03 20:17:46" to "yyyy-MM-dd'T'HH:mm:ss"
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.parse("2020-04-03 20:17:46")
its giving java.text.parseException always
Just for the case you are using Java 8 or above, make use of java.time.
See this simple example:
public static void main(String[] args) {
// example datetime
String datetime = "2020-04-03 20:17:46";
// create a formatter that parses datetimes of this pattern
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// then parse the datetime with that formatter
LocalDateTime ldt = LocalDateTime.parse(datetime, parserDtf);
// in order to output the parsed datetime, use the default formatter (implicitly)
System.out.println(ldt);
// or format it in a totally different way
System.out.println(ldt.format(
DateTimeFormatter.ofPattern("EEE, dd. 'of' MMM 'at' hh-mm-ss a",
Locale.ENGLISH)
)
);
}
This outputs
2020-04-03T20:17:46
Fri, 03. of Apr at 08-17-46 PM
Please note that this doesn't consider any time zone or offset, it just represents a date and time consisting of the passed or parsed years, months, days, hours, minutes and seconds, nothing else.
Do not use Date/Time API from java.util.* as most of them are now outdated. Use java.time API instead.
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) throws IOException {
String strDatetime = "2020-04-03 20:17:46";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDate = LocalDateTime.parse(strDatetime, formatter);
System.out.println(parsedDate);
}
}
Output:
2020-04-03T20:17:46
Learn more about DateTimeFormatter at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Could this help you? http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
First you need to parse the String with the old format, you will get a Date object. Then Create a new SimpleDateFormat with your new format, then you can format the Date object.
String dateString = "2020-04-03 20:17:46";
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
String formattedDate = output.format(date);
It do not work that way directly but if you still want to do it then, here is the process.
Create an object of SimpleDateFormat with pattern "yyyy-MM-dd HH:mm:ss")
use this to parse the string. Ultimately you are going to get date in both cases. Is there any specific reason for using T in pattern for dates which do not contain them?
Use LocalDateTime.
Timestamp timestamp = Timestamp.parse("2020-04-03 20:17:46");
LocalDateTime localDateTime = timestamp.toLocalDateTime();
System.out.println(localDateTime); // 2020-04-03T20:17:46

Parse ISO-8601 Datetime

It seems the proper form of timestamp to parse ISO-8601 in Java looks like:
"2020-02-03T23:40:17+00:00";
However mine looks like:
"2020-02-03T23:40:17+0000";
How can I parse this properly?
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class TestTime {
public static void main(String[] args) {
String ts = "2020-02-03T23:40:17+0000";
DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
OffsetDateTime offsetDateTime = OffsetDateTime.parse(ts, timeFormatter);
long timestamp = offsetDateTime.toEpochSecond() * 1000;
}
}
You could pass a pattern to the DateTimeFormatter:
String ts = "2020-02-03T23:40:17+0000";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZZZ");
OffsetDateTime offsetDateTime = OffsetDateTime.parse(ts, timeFormatter);
Note that the correct pattern for the offset is ZZZ instead of X or XXXX, which becomes obvious when, for example, formatting the parsed date-time back to a string:
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX");
OffsetDateTime offsetDateTime = OffsetDateTime.parse(ts, timeFormatter);
System.out.println(offsetDateTime.format(timeFormatter));
2020-02-03T23:40:17Z
While when using ZZZ, it will format like 2020-02-03T23:40:17+0000. See the documentation for DateTimeFormatter.

convert date from 2013-08-22T10:47:12+02:00 to 2013-08-22 10:47:12

Hy guys,
I would like to know how convert date with timezone like 2013-08-22T10:47:12+02:00 to another date 2013-08-22 10:47:12.
I try to do that with SimpleDateFormat object, but I have the same exception:
java.text.ParseException: Unparseable date: "2013-08-22T10:47:12+02:00"
Can you help me? thanks
UPDATE
I show here my failing code:
String CURRENT_TIME_PATTERN ="yyyy-MM-dd'T'HH:mm:yyX";
String NEW_TIME_PATTERN ="yyyy-MM-dd HH:mm:ss";
String data="2013-08-22T10:47:12+02:00";
SimpleDateFormat sdf = new SimpleDateFormat(CURRENT_TIME_PATTERN);
SimpleDateFormat output = new SimpleDateFormat(NEW_TIME_PATTERN);
Date d = sdf.parse(data);
String formattedTime = output.format(d);
System.out.println(formattedTime);
In this manner I will have exception over invalid parameter 'X'.
If I use this pattern String CURRENT_TIME_PATTERN ="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";, I'll get unparsable date exception.
I would suggest using Joda-Time to do any date and time formatting / parsing.
With the following imports:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
And the following code:
String input = "2013-08-22T10:47:12+02:00";
DateTimeFormatter formatterA = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTimeFormatter formatterB = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatterA.parseDateTime(input);
String output = dateTime.toString(formatterB);
You should try this if you always have T within your String :
String s = "2013-08-22T10:47:12+02:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:yyX"); // here X is for ISO 8601 time zone
Date parseDate = formatter.parse(s);
formatter.applyPattern("yyyy-MM-dd HH:mm:yy");
String formattedStr = formatter.format(parseDate);
System.out.println(formattedStr);
doc for ISO 8601 time zone
Update : removed String#replace() method and changed the formatter pattern to "yyyy-MM-dd'T'HH:mm:yyX".
Try this..
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String date = "2013-08-22T10:47:12+02:00";
Date date1 = dateFormat.parse(date);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String myDate = dateFormat1.format(date1);
System.out.println("Date :: " + myDate);

Categories