SimpleDateFormat not parsing - java

There are a million threads about the SimpleDateFormat class out there and I am having trouble, too:
Here's my little test code
SimpleDateFormat dateReader = new SimpleDateFormat("EEE, dd LLL YYYY HH:mm:ss Z", Locale.ENGLISH);
Calendar date = Calendar.getInstance();
try {
date.setTime(dateReader.parse(dateReader.format(date.getTime())));
} catch (ParseException e) {
e.printStackTrace();
}
One might think, that the current date in the correct format would be parsed correctly and this would run through without trouble but instead I get an exception java.text.ParseException: Unparseable date: "Fri, 11 Aug 2017 15:44:48 +0200"
Finally, I just want to parse a date like "Thu, 03 Aug 2017 20:10:00 +0200". I believe I have the right pattern for that.
I have no clue right now, what is wrong with it.
EDIT
The difference to the other questions is the pattern used. If you see the answer it shows that the pattern has been used incorrectly whereas most other questions have a totally wrong pattern or the wrong local. There might be a duplicate out there somewhere – but out of these many similarly named questions it is possibly faster to simply leave this as an own question.

I think your problem is on the year format use 'yyyy' instead of 'YYYY'.
SimpleDateFormat dateReader = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
try {
dateReader.parse("Thu, 03 Aug 2017 20:10:00 +0200");
} catch (ParseException e) {
e.printStackTrace();
}

Related

SimpleDateFormat parse off by 5 hours - Timezone issue?

Because of the consistency of the problem, and the fact that I am in GMT-5, I believe this to be a timezone issue. My code is below
MediaMetadataRetriever mdr = new MediaMetadataRetriever();
mdr.setDataSource(path);
date = mdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE);
try {
date = new SimpleDateFormat("MMM dd, yyyy h:mm a", Locale.getDefault()).format(new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.getDefault()).parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
Several things I did to fix it include the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.getDefault());
sdf.setTimezone(TimeZone.getDefaultTimezone);
try {
date = new SimpleDateFormat("MMM dd, yyyy h:mm a", Locale.getDefault()).format(sdf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
However, nothing changed. I would like to be able to use the default timezone for each device.
Any help is appreciated
EDIT: So the timezone works if I put
sdf.setTimeZone(TimeZone.getTimeZone("Eastern Standard Time"));
but not with
sdf.setTimeZone(TimeZone.getDefault());
Also, here is some sample input/output with the TimeZone.getDefault() method:
input: 20170121T212723 output: Jan 22, 2017 2:27 am (note how the raw date/time is January 21st, but the formatted one is January 22nd) Expected output would be Jan 21, 2017 9:27 pm
So maybe this question is more about why doesn't TimeZone.getDefault() return the right timezone?
Maybe it will be useful for someone.
The reason is that TimeZone.getDefault () returns a response in the form of a ZoneInfo object while getTimeZone ("Eastern Standard Time") returns a response in the form of a SimpleTimeZone object.
So this solution worked for me in kotlin (I think the result will be the same in java):
sdf.timeZone(TimeZone.getTimeZone(TimeZone.getDefault().toString()))

Issues parsing a String into a Calendar in Java

When I try the following code,
public static void main(String[] args) throws ParseException{
try {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
calendar.setTime(sdf.parse("Sun Feb 22 18:02:51 FET 2015"));
} catch (Exception e) {
e.printStackTrace();
}
}
I systematically get
java.text.ParseException: Unparseable date: "Sun Feb 22 18:02:51 FET 2015"
at java.text.DateFormat.parse(DateFormat.java:357)
at foo.Sample.main(LogEntry.java:131)
I realize that my issue is the FET timezone. That is a valid timezone. I have tried different things including using Locale.English but to no avail.
My issue seems to be due to the timezone as explained here.
EDIT
The following does not work either
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
Here is another post I found but didn't help me.
Java doesn't seem to support FET.
Use MSK.

SimpleDateFormat: unexpected results and unexpected parse exceptions

I'm having huge difficulties with simple date format. First of all, I know not all tutorials on all sites are actually good, but the fact that all non trivial formats (not dd/MM/yyyy) gave a parse exception (plus my own tests don't work as expected) is rather frustrating to me.
This is the site in question: http://www.mkyong.com/java/how-to-convert-string-to-date-java/
And I don't understand why something as simple as:
private static void unexpectedFailure() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
Throws a parse exception.
Also besides that, I'm trying to parse my own dates. This code gives strange results (unexpected I would say):
public static void doSomething(List<String> list) {
Iterator<String> iter = list.iterator();
String[] line = iter.next().split(" ");
System.out.println(Arrays.toString(line));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
format.setLenient(true);
try {
System.out.println(line[0]+" "+line[1]);
System.out.println(format.parse(line[0]+" "+line[1]));
} catch (ParseException e) {
System.out.println("In theory this should not get caught.");
}
}
Prints out this:
[06/08/2015, 13:51:29:849, DEBUG, etc...]
06/08/2015 13:51:29:849
Thu Aug 06 13:51:29 EEST 2015
Thu Aug 06 13:51:29 EEST 2015 WHAT? WHY?
EDIT I'll try and explain. In my last code snippet I'm just trying to determine if the string is a date, and it passes "the test". However when I'm printing it out the format is simply bizzare. I'm starting to think that is because I'm printing a date. How can I even print a DateFormat? What I was expecting was dd/MM/yyyy hh:mm:ss not ddd MMM 06? hh:mm:ss G YYYY
And I don't understand why something as simple as:
(code snipped)
Throws a parse exception.
My guess is that it's tripping up over Jun which may not be a valid month abbreviation in your system default locale. I suggest you specify the locale in your SimpleDateFormat constructor:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Then you're dealing with a locale which definitely has Jun as a month abbreviation.
That said, where possible I'd suggest using numeric formats where possibly, ideally ones following ISO-8601, e.g.
yyyy-MM-dd'T'HH:mm:ss
However when I'm printing it out the format is simply bizzare.
No it's not. You're effectively using
Date date = format.parse(line[0]+" "+line[1]);
System.out.println(date);
So that's calling Date.toString(), documented as:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So that's working as expected. However, you want to format the date using your SimpleDateFormat - so you need to call format:
System.out.println(format.format(date));
Of course that just checks that it can round-trip, basically.
As a side note, I suspect you want HH (24-hour clock) instead of hh (12-hour clock) in your format string.

Convert String to Date error parsing

I have looked at many examples and can still not find an answer to match my problem. I have now been stuck for an hour and need help.
I have many strings that are formated like this:
Wed, 06 Nov 2013 18:14:02
I have created a function to convert these strings into Date:
private static Date toDate(String pubDateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
pubDateString = pubDateString.substring(0, 25);
Date date = null;
try {
date = dateFormat.parse(pubDateString);
} catch (ParseException e1) {
e1.printStackTrace();
}
return date;
}
What I get is a ParseException:
java.text.ParseException: Unparseable date: "Wed, 06 Nov 2013 18:14:02"
Could anyone help me on my first challenge? Thanks.
edit : I tried HH, and kk
(When I originally answered the question, the format string used hh - it has since been changed.)
You're using hh for the hours part, which is a 12-hour format - but providing a string which uses "18". You want HH.
Additionally, I'd suggest explicitly specifying the locale if you know that the values will always use English names.
I've verified that if you specify the locale explicitly, the code definitely works - at least under Oracle's Java 7 implementation:
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss",
Locale.US);
If it wasn't working for you without the locale being specified (but with HH) that's probably why - presumably your system locale isn't English, so it was expecting different month and day names.

Exception in parsing date format [duplicate]

This question already has answers here:
Date Format JAVA
(5 answers)
Closed 9 years ago.
I have a date in the following format
//input date
Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)
//output date format
I want to change this to "dd-mm-yyyy, hh:mm:ss".
I get the input date format from db. I have to change that into output date format which i will be showing it in a grid.
I tried the following code.
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
try
{
Date date = outputDate.parse(facade.getDate.toString()); **//getting exception here**
outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
Date date1 = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").parse(outputDate
.format(date));
facade.setDate(date1);
}catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting
java.text.ParseException: Unparseable date: "2013-06-06 00:00:00.0".
Any help..
"2013-06-06 00:00:00.0" does not match "dd-mm-yyyy, hh:mm:ss" your format should be "dd-MM-yyyy hh:mm:ss" instead
But, looking at your code I'm guessing facade.getDate is actually a java.sql.Timestamp which inherits from java.util.Date so you can directly pass it to the format like so
new SimpleDateFormat("dd-MM-yyyy, hh:mm:ss").format(facade.getDate)
Here's some code which works for me:
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
String input = "Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time)";
DateFormat inputFormat = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'z",
Locale.ENGLISH);
Date date = inputFormat.parse(input);
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",
Locale.ENGLISH);
outputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String output = outputFormat.format(date);
System.out.println(output);
}
}
Things to consider:
You need to work out your output time zone. Currently I've got it set to UTC, but that may not be what you want.
You really need to take a step back and think things through. You've clearly got two different formats - you're trying to convert from one to the other. So creating three different SimpleDateFormat objects all with the same format is never going to work.
You need to read documentation carefully... in SimpleDateFormat, M means month and m means minute; h uses the 12-hour clock and H uses the 24-hour clock.
This is assuming you actually need to start with a string though. If getDate is already a Date or a Timestamp, you can ignore the first part - just use the output part of the above code. You should avoid unnecessary string conversions wherever possible.
Note that dd-MM-yyyy is a slightly unusual format - are you sure you don't actually want yyyy-MM-dd which is more common (and sortable)?
DateFormat outputDate = new SimpleDateFormat("yyyy-dd-mm hh:mm:ss");
try {
Date date = outputDate.parse("2013-06-06 00:00:00.0");
System.out.println(new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss").format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
works well, line 1 was incorrect. Your SimpleDateFormat.parse needs to be in the exact format of the input date. Then you want to output it in a different format so you make another one and set the format then call SimpleDateFormat.format(date) and I put a println on it.
Fault is here
DateFormat outputDate = new SimpleDateFormat("dd-mm-yyyy, hh:mm:ss");
pattern should be equals to Thu Jun 06 2013 00:00:00 GMT+0530 (India Standard Time). not to your out put strings pattern.
#Test
public void test() throws ParseException {
SimpleDateFormat sdf_org = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
Date d = sdf_org.parse("Thu Jun 06 2013 00:00:00 GMT+0530");
SimpleDateFormat sdf_target = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSS");
System.out.println(sdf_target.format(d));
}
output console : 2013-30-06 03:30:00.000

Categories