Reputation: 1644
I'm getting this date from bing search and have difficulty to parse it to date, I need the time as well.
""2021-09-02T13:16:00.0000000Z""
I'm doing this:
public static Date parseDate(String publishedDate) {
String dateStr = publishedDate.replaceFirst("T", "");
SimpleDateFormat formatter = null;
if (publishedDate.length() > 10) {
formatter = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
} else {
formatter = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = null;
try {
date = formatter.parse(publishedDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
getting the following error:
java.text.ParseException: Unparseable date: ""2021-09-02T13:16:00.0000000Z""
at java.base/java.text.DateFormat.parse(DateFormat.java:396)
Upvotes: 0
Views: 1302
Reputation: 125
What you are dealing with is called Time Stamp, there are Duration and INSTANT classes to deal with it. This page explain it all https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
As @Basil Bourque suggested, we dont need DateTimeFormatter because Instant.parse() by default uses UTC. Also, we can use OffsetDateTime instead of ZonedDateTime (more detailed),
String date = "2021-09-02T13:16:00.0000000Z";
Instant timeStamp = Instant.parse(date);
// To get Time or Date," with Instant you must provide time-zone too"
ZonedDateTime dateTimeZone = ZonedDateTime.ofInstant(timeStamp, ZoneOffset.UTC);
System.out.println(dateTimeZone);
System.out.println(dateTimeZone.toLocalDate());// can also be tolocalTime
Upvotes: 1
Reputation: 86379
Like many others I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Your string contains double quotes first and last. You can deal with them in two ways:
Instant.parse()
will parse your string, and you’re done.For parsing the quotes use the following formatter:
private static final DateTimeFormatter BING_INSTANT_PARSER
= new DateTimeFormatterBuilder().appendLiteral('"')
.append(DateTimeFormatter.ISO_INSTANT)
.appendLiteral('"')
.toFormatter();
Then parse like this:
String stringFromBing = "\"2021-09-02T13:16:00.0000000Z\"";
Instant instant = BING_INSTANT_PARSER.parse(stringFromBing, Instant::from);
System.out.println("String to parse: " + stringFromBing);
System.out.println("Result: " + instant);
Output:
String to parse: "2021-09-02T13:16:00.0000000Z" Result: 2021-09-02T13:16:00Z
Assuming that your string always comes with the Z
at the end, denoting UTC, Instant
is the correct class to use. OffsetDateTime
and ZonedDateTime
will work too, but I consider them overkill. You don’t want to use LocalDateTime
since you would then throw away the essential information that the string is in UTC.
Oracle tutorial: Date Time explaining how to use java.time.
Upvotes: 3