How to parse date String containing Locale - java

I have a date String "Sat Jan 28 00:00:00 IST 2012" and I am trying to parse it using DateTimeFormatter of Joda. I have the following code, dont know where, it went wrong.
DateTimeFormatter dateFmt = DateTimeFormat
.forPattern("EEE MMM dd HH:mm:SS ZZZ yyyy");
DateTime dateTime = dateFmt.parseDateTime(dateString);
Exception : java.lang.IllegalArgumentException: Invalid format: "Sat Jan 28 00:00:00 IST 2012" is malformed at "IST 2012". Please help me to get thro this. Thanks for any help.

IST is not recognized timezone by API, It can recognize only one of the timezone from getAvailableIds()

Use zzz (lowercase), not ZZZ (uppercase). From the API docs:
z time zone text Pacific Standard Time; PST
Z time zone offset/id zone -0800; -08:00; America/Los_Angeles

I don't know why, but it is working if I use SimpleDateFormat instead of DateTimeFormatter.
CODE:
public static void main(String[] args) throws ParseException {
String FORMAT = "EEE MMM dd HH:mm:SS zzz yyyy";
String dateString = "Sat Jan 28 00:00:00 IST 2012";
SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT);
Date date = dateFormat.parse(dateString);
System.out.println(new DateTime(date));
DateTimeFormatter dateFmt = DateTimeFormat.forPattern(FORMAT);
// System.out.println(dateFmt.parseLocalDateTime(dateString));
// System.out.println(dateFmt.parseDateTime(dateString));
System.out.println(dateFmt.parseLocalTime(dateString));
}

Related

Local Date to UTC conversion

I'm trying to convert system local date to UTC. Below is my code and it looks working for MST and EST formats. But, it is not working as expected.
String inputDate = "Wed Apr 13 04:00:00 IST 2022";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date date = sdf.parse(inputDate);
DateFormat formatUTC = new SimpleDateFormat("MM/dd/yyyy");
formatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
String result = formatUTC.format(date);
System.out.print(result); // 04/13/2022
I see that IST zone is 5hrs 30mins ahead from the UTC universal time. So, I should get 04/12/2022 for the given input. But, getting 04/13/2022. what am I doing wrong here? Please advise.
Try setting the timezone for inputDate as well. Try the below code:
String inputDate = "Wed Apr 13 04:00:00 IST 2022";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
Date date = sdf.parse(inputDate);
DateFormat formatUTC = new SimpleDateFormat("MM/dd/yyyy");
formatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
String result = formatUTC.format(date);
System.out.print(result);
Take a look at this answer.

Trouble formatting date in Java [duplicate]

This question already has answers here:
DateTimeParse Exception
(2 answers)
Closed 2 years ago.
I've tried several methods with Java Joda Time, Date Time with locale and commons-lang and can't get this date formatted.
Input
Mon Dec 28 15:18:16 UTC 2020
Output
Desired output format yyyy-MM-dd HH:mm:ss.SSS
When I use a format pattern like EEE MMM dd HH:mm:ss Z YYYY the date is off my a couple days and the timezone seems completely wrong.
Formatter:
private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
.withLocale(Locale.US)
.withZone(ZoneId.systemDefault());
DateUtils.parseDate (Optional
.ofNullable(record)
.map(CustomerModel::getCustomerAudit)
.map(customerAudit::getCreated)
.map(auditItem::getDate).get ().toString (), "EEE MMM dd HH:mm:ss YYYY")
When debugging parsing issues, if possible, reverse the operation and generate the text you're supposed to be parsing, to verify the parsing rules, i.e. the date format string. This applies to date parsing, JAXB parsing, and any other (de)serializing operation that is bi-directional. It makes finding conversion rule issues a lot easier.
So, let us check the format string in the question, with the shown date value:
ZonedDateTime dateTime = ZonedDateTime.of(2020, 12, 28, 15, 18, 16, 0, ZoneOffset.UTC);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z YYYY", Locale.US);
System.out.println(dateTime.format(fmt));
Output
Mon Dec 28 15:18:16 +0000 2021
Oops! That doesn't fit the expected output, aka the input we desire to parse:
Mon Dec 28 15:18:16 UTC 2020
So what went wrong?
The year is wrong because it's supposed to be uuuu (year), not YYYY (week-based-year).
The time zone is wrong because Z does support a text representation. Use VV or z instead.
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse("Mon Dec 28 15:18:16 UTC 2020", fmt);
System.out.println(dateTime);
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS")));
Output
2020-12-28T15:18:16Z[UTC]
2020-12-28 15:18:16.000
As you can see, it now parsed correctly.
The code in the question makes little sense:
It is formatting a Date value to text using toString(), just to attempt parsing that back.
It is using Optional for simple null-handling (which is discouraged), but then unconditionally calling get(), which means a null value will throw exception anyway.
The code should be:
record.getCustomerAudit().getCreated().getDate().toInstant()
This of course makes the entire question moot.
Works fine for me.
String s = "Mon Dec 28 15:18:16 UTC 2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV yyyy",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(s, formatter);
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
System.out.println(zdt.format(formatter));
Output is
2020-12-28 15:18:16.000
Am I missing something?
Have you tried with SimpleDateFormat?
String dateString = "Mon Dec 28 15:18:16 UTC 2020";
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
System.out.println(output.format(input.parse(dateString)));
With timezone:
String dateString = "Mon Dec 28 15:18:16 UTC 2020";
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd z HH:mm:ss.SSS");
input.setTimeZone(TimeZone.getTimeZone("UTC"));
output.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(output.format(input.parse(dateString)));

Old Date Formatting incompatible with Java 8 ZonedDateTime API

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.

Parse date with AEDT and AEST time zone in java

I am trying to parse a string of format
Thu Apr 07 11:45:28 AEST 2016
into date object. My code looks like following:
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
try{
Date time = parserSDF.parse("Sat Feb 01 15:00:19 AEDT 2014");
}catch(Exception e){
e.printStackTrace();
}
But I am getting a 'parse error'. I cannot change the input format of the date and I also cannot set my timezone to a static value as this code is to be run on andorid device. How can I parse this string into date ?
Using the java.time framework (JSR 310), you can do:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy");
ZonedDateTime zdt = ZonedDateTime.parse("Sat Feb 01 15:00:19 AEDT 2014", dtf);
System.out.println(zdt);
…which prints:
2014-02-01T15:00:19+11:00[Australia/Sydney]
Though why it picks Sydney instead of Melbourne I am not sure.

Unparseable date in java -convert from Date into Calendar

I need to convert from Date(the object :insuree.getBirthDate()) into Calendar(the object : request_MDP.setBIRTH_DATE)
but i get the error :
21/02/13 15:20:26 ERROR [MdmInsureeService]: ServiceProxy Update
exception: 'Unparseable date: "Mon Nov 15 15:00:00 IST 1982"' 21/02/13
15:20:26 ERROR [MdmInsureeService]: ServiceProxy Update exception
(toString): 'java.text.ParseException: Unparseable date: "Mon Nov 15
15:00:00 IST 1982"
This is my code :
DateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date_MDP =(Date)formatter.parse(insuree.getBirthDate().toString());
Calendar cal_MDP=Calendar.getInstance();
cal_MDP.setTime(date_MDP);
request_MDP.setBIRTH_DATE(cal_MDP);
How can I convert the Date(insuree.getBirthDate()) into Calendar(setBIRTH_DATE) ?
Thanks
try this code:
SimpleDateFormat df = new SimpleDateFormat("KK:mm aa");
Date date = df.parse("10:30 PM");
System.out.print(date);
Calendar cal = GregorianCalendar.getInstance();
cal.setTimeInMillis(date.getTime());
System.out.print(cal.getTime());
Is it possible that you run this code on a system with a non-English locale? Such a locale might not recognize the weekday or month in your example date ("Mon Nov 15 15:00:00 IST 1982"), because it uses different names (e.g. "Tue" would be "Di" in German).
Replace the first line in your snippet with
DateFormat formatter =
new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy", Locale.US);
and it will work with your example date. Either way, you have to use the same format and locale that was used to generate those date strings. Maybe you can even convince the generator to use some standard format like ISO 8601.

Categories