I need help parsing the String date
"Thu Oct 22 13:51:51 CEST 2015"
with SimpleDateFormat, but I'm not able to find the correct pattern.
Here is what I've tried
String date = "Thu Oct 22 13:51:51 CEST 2015";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("E M d H:m:s z y");
d1 = dateFormat.parse(date);
} catch (ParseException e1) {
Log.e(null, String.valueOf(e1));
}
I get back the error:
java.text.ParseException: Unparseable date: "Thu Oct 22 13:51:51 CEST 2015" (at offset 0)
UPDATE
I tried the solution below by durron597 adapting it to my needs:
String date = "Thu Oct 22 13:51:51 CEST 2015";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy", Locale.US);
Date d1 = dateFormat.parse(date);
} catch (ParseException e1) {
Log.e("null", String.valueOf(e1));
}
but in the logcat I keep getting the error:
java.text.ParseException: Unparseable date: "Thu Oct 22 13:51:51 CEST 2015" (at offset 20)
Use more letters for the longer versions of the Date elements.
In particular the problem in your case was probably the Month portion, which you can see from this part of the Javadoc for SimpleDateFormat:
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
You only had one character for Month, it tried to interpet it as a number, found a letter, and failed.
You also need to specify the US locale, as these are United States dates.
Specify the Locale to use in translating the name of the day of the week, “Thu”. You are in Italy (it says so in your profile); when I use Locale.Italy on my machine, I get the same error as you do. If you specify Locale.US as in the below code, it should work.
Update: Android doesn't support three letter time zones, according to this:
Other than the special cases "UTC" and "GMT" (which are synonymous in this context, both corresponding to UTC), Android does not support the deprecated three-letter time zone IDs used in Java 1.1.
You should be able to replace your Europe time zone with the full name of the time zone defined in the official “tz” time zone database (formerly known as Olson database). For example, Europe/Rome instead of "CEST".
Try this instead:
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy", Locale.US);
date.replace("CEST", "Europe/Rome");
Date d1 = dateFormat.parse(date);
Here's a full working example:
public class DateExample {
public static void main(String[] args) {
String date = "Thu Oct 22 13:51:51 CEST 2015";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy", Locale.US);
date.replace("CEST", "Europe/Rome");
Date d1 = dateFormat.parse(date);
System.out.println(d1);
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
Output:
Thu Oct 22 06:51:51 CDT 2015
Related
I am updating my old date formatting code to Java 8 and trying the ZonedDateTime API.
The format of date is same as the Javascript Date object format, e.g. -
Thu May 25 2017 10:00:00 GMT+1200 (New Zealand Standard Time)
I was using the below format previously -
EEE MMM dd yyyy hh:mm:ss 'GMT'Z '('zzzz')'
This format fails to parse the date string using DateTimeFormatter.ofPattern method.
Here's the code:
public static final String DATE_FORMAT = "EEE MMM dd yyyy hh:mm:ss 'GMT'Z '('zzzz')'";
public static void main(String[] args) throws ParseException {
String sDate = "Thu May 25 2017 10:00:00 GMT+1200 (New Zealand Standard Time)";
parseDate(sDate);
}
private static void parseDate(String sDate) throws ParseException {
// works
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date oldDate = dateFormat.parse(sDate);
//FIXME: can't parse?!
ZonedDateTime newDate = ZonedDateTime.parse(
sDate, DateTimeFormatter.ofPattern(DATE_FORMAT)); // <- this is the line 25!
}
Here's my full code for reference that can be compiled and run - https://gist.github.com/bhabanism/470e03db54981ad6ddedbba316dcaa9a
This fails at line#25 with:
Exception in thread "main" java.time.format.DateTimeParseException:
Text 'Thu May 25 2017 10:00:00 GMT+1200 (New Zealand Standard Time)'
could not be parsed: Unable to obtain ZonedDateTime from
TemporalAccessor: {HourOfAmPm=10, MilliOfSecond=0, MinuteOfHour=0,
OffsetSeconds=43200, MicroOfSecond=0, NanoOfSecond=0,
SecondOfMinute=0},ISO,Pacific/Auckland resolved to 2017-05-25 of type
java.time.format.Parsed
Note, I can't change the input format of the Date, it has to be
Thu May 25 2017 10:00:00 GMT+1200 (New Zealand Standard Time)
I can surely modify the formatter
EEE MMM dd yyyy hh:mm:ss 'GMT'Z '('zzzz')'
It seems there was a bug in your format string all the time. Lowercase hh is for hour within AM or PM, in the range 1 through 12. Since you don’t have AM/PM in your string, I suspect this was never what you wanted, and I wonder how the error went unnoticed.
Uppercase HH is for hour of day, 0 through 23:
public static final String DATE_FORMAT = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z '('zzzz')'";
With this change both the old and the new way of parsing works on my computer.
When adding Locale.ENGLISH to both formatters, that is. You may want to do the same.
The results I get are
Thu May 25 00:00:00 CEST 2017
2017-05-25T10:00+12:00[Pacific/Auckland]
Since CEST is 2 hours ahead of UTC, this is the same point in time, only rendered differently.
I have an Object with the following text:
System.out.println("My date: " + valor);
and it prints
My date: Thu Jan 01 13:00:00 CST 2015
I want to convert this text to a Date variable, this is my code:
dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy",new Locale("es","MX"));
try {
Date dateToString = dateFormat.parse(valor.toString());
} catch (ParseException e) {
new Date();
}
I always get current date, I've tried several combinations for SimpleDateFormat but none works, what's the proper way to convert my Object to a Date variable
Your format doesn't include time zone (z) and you shouldn't swallow an Exception without logging it (which is how I found the error). Something like,
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
Date dateToString = dateFormat.parse("Thu Jan 01 13:00:00 CST 2015");
System.out.println(dateFormat.format(dateToString));
} catch (ParseException e) {
e.printStackTrace();
}
Output is
Thu Jan 01 13:00:00 CST 2015
Looks like your date format isn't accounting for the timezone. Maybe try
EEE MMM dd HH:mm:ss z yyyy
See Java Docs
I would like to extract date and year from the following string and convert it to a Data Object in Java.
Mon Jul 07 19:18:26 CEST 2014
How can I extract only date and year (in this case, 2014-07-07) from the text in a sophisticated way?
SimpleDateFormat s = new SimpleDateFormat("dd/MMM/yyyy");
String dateInString = "Mon Jul 07 19:18:26 CEST 2014";
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = s.parse(dateInString.split(" ")[2]+"/"+dateInString.split(" ")[1]+"/"+dateInString.split(" ")[5]);
System.out.println(new SimpleDateFormat("YYYY-MM-dd").format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This should work for you, I splitted your String, then put it to a date format and then formatted it the way you wanted it to be, assumed you wanted the months as the second parameter after the year, if thats not the case you can simply change the 'MM' to 'dd' and the 'dd' to 'MM'.
For Java 7 or below, use a SimpleDateFormat for parsing and formatting:
Locale dateLocale = Locale.US;
SimpleDateFormat inFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", dateLocale);
Date date = inFormat.parse("Mon Jul 07 19:18:26 CEST 2014");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd", dateLocale);
System.out.println(outFormat.format(date));
Since Java 8, you can use DateTimeFormatter:
Locale dateLocale = Locale.US;
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", dateLocale);
TemporalAccessor date = inFormatter.parse("Mon Jul 07 19:18:26 CEST 2014");
DateTimeFormatter outFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
System.out.println(outFormatter.format(date));
I have a date string:
Thu Feb 20 08:00:00 EET 1992
And using this code to format it:
String datePatternFrom = "EEE MMM dd HH:mm:ss ZZZ yyyy";
String datePatternTo = "MMM dd, yyyy";
String prettyDate = "";
try {
DateFormat fromFormatter = new SimpleDateFormat(datePatternFrom);
Date date = (Date)fromFormatter.parse(userBirthday.toString());
DateFormat toFormatter = new SimpleDateFormat(datePatternTo);
prettyDate = toFormatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
Why I'am getting the exception?
java.text.ParseException: Unparseable date: "Thu Feb 20 08:00:00 EET 1992" (at offset 0)
The problem is with the weekday and month and your locale.
Thu is English, so you have to tell the parser that it should use English weekdays:
DateFormat fromFormatter = new SimpleDateFormat(datePatternFrom, Locale.US);
This will work for your pattern.
If you do not specify a locale, the default will be used, which is not always an English one. ;-)
It could be your locale. Try making a SDF with datePatternFrom, give it a date to format and print that somewhere. See what pops up.
Probably your userBirthday object was not created as a java.util.Date object. Can you try a System.out.println(userBirthday.getClass().getName());?
I have the following Java:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
cal.set(2011, Calendar.APRIL, 1);
out.println(formatter.format(cal.getTime()));
out.println();
Date date;
try {
date = formatter
.parse("Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)");
} catch (ParseException e) {
out.println("Failed to parse date: " + e.getMessage());
e.printStackTrace(out);
}
This is in a servlet, and the Calendar-constructed date comes out as:
Fri Apr 01 2011 16:42:24 EDT-0400 (Eastern Daylight Time)
This looks like the same format as the date string I'm trying to parse, except for EDT-0400 versus the desired GMT-0400. The code fails when trying to parse the date string:
java.text.ParseException: Unparseable date: "Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)"
How can I parse such a string? This is coming from a JavaScript date in a Sencha Touch 1.1.1 model, stored in WebSQL local storage.
For some reason GMT-0400 isnt' working, and UTC-0400 is working. You can replace GMT with UTC.
Note that this part will be completely ignored - the timezone will be resolved from what's found in the brackets (at least on my machine, JDK 6)
I debugged SimpleDateFormat and it seems that it will only parse GMT-04:00 but not GMT-0400.
It will accept UTC-0400, however it will throw away the hours/minutes modifier and will incorrectly parse it as UTC. (This happens with any other timezone designation, except for GMT)
It will also parse -0400 correctly, so the most robust solution is probably to simply remove GMT from your date string.
The upshot of the story is that SimpleDateFormat is anything but simple.
Update: Another lesson is that I could've saved a lot of time by passing a ParsePosition object to the parse() method:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zzzz", Locale.ENGLISH);
Date date;
ParsePosition pos = new ParsePosition( 0 );
date = formatter
.parse("Fri Apr 01 2011 00:00:00 UTC-0400", pos);
System.out.println( pos.getIndex() );
Will print out 28, indicating that the parsing ended at character index 28, just after UTC.