Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unable to parse date exception

I have date and time on string type 20/03/2018, 18:20:44 Is it possible to change it to date format in java? I tried this code:

public static Date getDate(String dateString) {
    DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("PST"));
    try {
        Date date = formatter.parse(dateString);
        return date;
    } catch (ParseException e) {
        logger.error("error while parsing milliseconds to date" + dateString, e);
    }
    return null;
}

I get unable to parse exception and returned with null

like image 506
Ashok Kumar Avatar asked Aug 20 '26 05:08

Ashok Kumar


2 Answers

You've used the wrong string replacements inside your simple date format, it should be dd/MM/yyyy, HH:mm:ss. Note the capitalisation of the HH as well, your time is in 24 hour format so it must be HH over hh

So with the applied changes your code will look like this:

public static Date getDate(String dateString) {
  DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss");
  formatter.setTimeZone(TimeZone.getTimeZone("PST"));
  try {
    return formatter.parse(dateString);
  } catch (ParseException e) {
    logger.error("error while parsing milliseconds to date" + dateString, e);
  }
  return null;
}

Read more on the various patterns available here, as an aside it is generally recommended to use the ISO 8601 format for dates, so yours would be yyyy-MM-ddTHH:mm:ss

like image 66
A. Bandtock Avatar answered Aug 21 '26 20:08

A. Bandtock


You should use the same format with input string:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
like image 42
xingbin Avatar answered Aug 21 '26 19:08

xingbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!