I've got a problem with the following date format: "Jan 15 2020 11:11:50.000 +0000". I need to parse the date into ms.
The odd behavior is that i can't use date.parse(). The function is always failing with "java.text.ParseException: Unparseable date: "Jan 15 2020 11:11:50.000 +0000";".
Someone got an idea how to manually parse the date or to change the date format within date.parse()?
Thanks all
With a ZonedDateTime and this pattern LLL d yyyy HH:mm:ss.SSS Z (DateTimeFormatter) you'll be able to handle it
String value = "Jan 15 2020 11:11:50.000 +0000";
DateTimeFormatter dt = DateTimeFormatter.ofPattern("LLL d yyyy HH:mm:ss.SSS Z", Locale.ENGLISH);
ZonedDateTime l = ZonedDateTime.parse(value, dt);
System.out.println(l.format(dt)); // Jan 15 2020 11:11:50.000 +0000
Related
I am trying to parse this (and many similar) dateString - "Wed Aug 26 2020 11:03:30 GMT-0500"
Looking at the SimpleDateFormat documentation, I was assuming that a pattern like this should work:
String dateFormat = "EEE MMM d yyyy HH:mm:ss z";
However, it doesn't. But the following format is able to parse
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'z";
But when I print the parsed date, I get the time with an hour added and offset reduced by an hour - Wed Aug 26 12:03:30 GMT-04:00 2020
What can I do to prevent this offset change?
Here is the sample code:
String dateStr = "Wed Aug 26 2020 11:03:30 GMT-0500";
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'z";
Date date = new SimpleDateFormat(dateFormat).parse(dateStr);
System.out.println("Original Date String : "+dateStr);
System.out.println("Original Date Object : "+date);
Output:
Original Date String : Wed Aug 26 2020 11:03:30 GMT-0500
Original Date Object : Wed Aug 26 12:03:30 GMT-04:00 2020
Use java.time.OffsetDateTime here because there is no zone in that String, just an offset and the classes you are using are outdated for good reasons... Get rid of java.util.Date and java.text.SimpleDateFormat.
See this example:
public static void main(String[] args) {
// provide the String to be parsed
String dateStr = "Wed Aug 26 2020 11:03:30 GMT-0500";
// provide a matching pattern
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'Z";
// create a formatter with this pattern and a suitable locale for unit names
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat, Locale.ENGLISH);
// parse the String to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dateStr, dtf);
// print the result in the default format
System.out.println("Default/ISO format:\t" + odt);
// and print it in your custom format
System.out.println("Custom format:\t\t" + odt.format(dtf));
}
Output:
Default/ISO format: 2020-08-26T11:03:30-05:00
Custom format: Wed Aug 26 2020 11:03:30 GMT-0500
I have this String
Fri, 07 Aug 2020 18:00:00 +0000
And I need to convert it to a LocalDateTime
I tryed several ways:
create a DateTimeFormatter and parse the String
String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss", Locale.getDefault());
LocalDateTime parsedDate = LocalDateTime.parse(publishedString, formatter);
Convert it to a Date with a SimpleDateFormat and then convert the resultDate to a LocalDateTime
String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Date date = dateFormatter.parse(publishedString);
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
both solution gives me the same exception:
java.time.format.DateTimeParseException: Text 'Fri, 07 Aug 2020 18:00:00 +0000' could not be parsed
at index 0 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
How can I convert that String?
I'd say use Locale.ROOT and don't forget the Z in the DateTimeFormatter class
String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss Z", Locale.ROOT);
LocalDateTime parsedDate = LocalDateTime.parse(dateString, formatter);
tl;dr
OffsetDateTime.parse(
"Fri, 07 Aug 2020 18:00:00 +0000" ,
DateTimeFormatter.RFC_1123_DATE_TIME
)
See this code run live at IdeOne.com.
LocalDateTime is the wrong class
Your input string contains +0000 which indicates an offset-from-UTC.
So you should not be using LocalDateTime. That class purposely lacks any concept of time zone or offset. With LocalDateTime, your string Fri, 07 Aug 2020 18:00:00 +0000 will become 6M on August 7th 2020, but we won't know if that is 6 PM in Tokyo Japan, 6 PM in Toulouse France, or 6 PM in Toledo Ohio US — all different moments several hours apart.
OffsetDateTime
Instead, this value should be parsed as OffsetDateTime.
Parsing
Your input's format is that of RFC 1123. That particular format is predefined in java.time.
String input = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter f = DateTimeFormatter.RFC_1123_DATE_TIME;
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2020-08-07T18:00Z
I understand that you need a LocalDateTime for an API that due to a design problem beyond your control is trying to use LocalDateTime for a point in time.
If an external contract dictates in which time zone or at which UTC offset the LocalDateTime is to be understood, LocalDateTime can be made to work, at least for 99.977 % of cases. You will still have a programming error waiting to happen on the day when some colleague programmer does not read the contract, a problem that we cannot solve in the code, only try to mitigate through good commenting.
If for example the contract says UTC, then we need to make sure we convert the time to UTC. And we need the offset from the string for doing so.
ZoneOffset contractualOffset = ZoneOffset.UTC;
String stringWeveGot = "Fri, 07 Aug 2020 18:00:00 +0000";
LocalDateTime convertedDateTime = OffsetDateTime
.parse(stringWeveGot, DateTimeFormatter.RFC_1123_DATE_TIME)
.withOffsetSameInstant(contractualOffset)
.toLocalDateTime();
System.out.println(convertedDateTime);
Output:
2020-08-07T18:00
If the offset in the string is required to be 0 already, you need to validate that it is, or errors will go unnoticed and users will get wrong results. For example:
OffsetDateTime parsedOdt = OffsetDateTime
.parse(stringWeveGot, DateTimeFormatter.RFC_1123_DATE_TIME);
if (! parsedOdt.getOffset().equals(contractualOffset)) {
throw new IllegalStateException("Offset must be " + contractualOffset
+ ", was " + parsedOdt.getOffset());
}
LocalDateTime convertedDateTime = parsedOdt.toLocalDateTime();
If the contract mentions some time zone, convert to that time zone. I am taking Australia/Victoria as an example.
ZoneId contractualZone = ZoneId.of("Australia/Victoria");
String stringWeveGot = "Fri, 07 Aug 2020 18:00:00 +0000";
LocalDateTime convertedDateTime = OffsetDateTime
.parse(stringWeveGot, DateTimeFormatter.RFC_1123_DATE_TIME)
.atZoneSameInstant(contractualZone)
.toLocalDateTime();
System.out.println(convertedDateTime);
2020-08-08T04:00
You will get an ambiguous result at time anomalies where the clock is turned backward, for example at the fall back when summer time (DST) ends.
What went wrong in your code?
The cause of your exception is explained here:
new SimpleDateFormat(“hh:mm a”, Locale.getDefault()).parse(“04:30 PM”) giving Unparseable exception
java DateTimeFormatterBuilder fails on testtime
need help in java code to get current date and time in below format :
newdate = "Mon, 13 Jul 2020 14:08:30 GMT"
After this I need to replace current date with earlier one:
vJsonfile1.replace(earlierdate," "+ newdate);
You can use ZonedDateTime and the RFC_1123 format to get the output you need:
DateTimeFormatter dtf = DateTimeFormatter.RFC_1123_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("GMT"));
System.out.println(dtf.format(zdt));
Wed, 15 Jul 2020 19:07:37 GMT
Note the 1123_DATE_TIME format doesnt play nice with North American Time zones so itll work as long as its GMT or European time zones otherwise below will suffice too:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z");
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(dtf.format(zdt));
Wed, 15 Jul 2020 14:13:22 CDT
Which will output the current time with the time zone its in.
Here is an example that formats your datetime and then changes the date portion of it:
ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z")));
zonedDateTime = ZonedDateTime.of(LocalDate.of(2020, 12, 15), zonedDateTime.toLocalTime(), zonedDateTime.getZone());
System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z")));
This code does exactly what you wanted it to do.
Output:
Mi, 15 Jul 2020 08:55:21 MESZ
Code:
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");
Date currentDate = new Date();
System.out.println(formatter.format(currentDate));
This question already has answers here:
How to convert date in to yyyy-MM-dd Format?
(6 answers)
How can I convert Date.toString back to Date?
(5 answers)
Java - Unparseable date
(3 answers)
Closed 5 years ago.
I got problem with date parse example date:
SimpleDateFormat parserSDF=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.getDefault());
parserSDF.parse("Wed Oct 16 00:00:00 CEST 2013");
got exception
Exacly I want parse this format date to yyyy-MM-dd
I try:
SimpleDateFormat parserSDF = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = parserSDF.parse("Wed Oct 16 00:00:00 CEST 2013");
take :
java.text.ParseException: Unparseable date: "Wed Oct 16 00:00:00 CEST 2013"
OK I change to and works :
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ENGLISH);
Date date = parserSDF.parse("Wed Oct 16 00:00:00 CEST 2013");
I'm going to assume that Locale.getDefault() for you is pl-PL since you seem to be in Poland.
English words in date strings therefore cause an unparseable date.
An appropriate Polish date String would be something like
"Wt paź 16 00:00:00 -0500 2013"
Otherwise, change your Locale to Locale.ENGLISH so that the SimpleDateFormat object can parse String dates with English words.
Instead of using Locale.default that you and others often don't know which default, you can decide by using locale.ENGLISH because I see your string date is format in English. If you are at other countries, the format will be different.
Here is my example code:
public static void main(String[] args) {
try {
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
Date date = parserSDF.parse("Wed Oct 16 00:00:00 CEST 2013");
System.out.println("date: " + date.toString());
} catch (ParseException ex) {
ex.printStackTrace();
}
}
The result will be : date: Wed Oct 16 05:00:00 ICT 2013. Or you can decide which part of this date to be printed, by using its fields.
Hope this help :)
I think the original Exception is due to Z in your format.
Per documentation:
Z Time zone RFC 822 time zone -0800
most likely you meant to use lower case z
I have used the following
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss zzz");
Date date = new Date();
String formattedDate= df.format(date);
Date dateWithTime = df.parse(formattedDate);
i got the formatted date as string when i conver this into date i got error like
java.text.ParseException: Unparseable date: "Tue Feb 26 11:45:43 IST 2013"
How would convert to date or how i format a current date and get as date?
I think your code wouldn't throw ParseException. But it sure would definitely yield wrong output. your format should be:
"dd-MM-yyyy hh:mm:ss zzz"
Note that
MM---> Months
mm---> Minutes
Test with your code with out correcting the format:
Sat Jan 26 06:24:07 GMT 2013
Test with your code with correcting the format:
Tue Feb 26 06:20:51 GMT 2013
The date format should be as follows as shown in the exception. Change it to -
EEE MMM d hh:mm:ss z yyyy
The correct simpledateformat will be
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Please refer the link for proper date formatting and parsing
SimpleDateFormat