Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse 'dd MMM yyyy'

How to convert date fromat from "dd MMM yyyy" to "yyyy-MM-dd"?

I know I have to use SimpleDatFormat but it doesn't work, neither does any solution from similar questions.

I have a date "18 Dec 2015" that I am trying to format but I get this

java.text.ParseException: Unparseable date: "18 Dec 2015"

Here's my code:

public String parseDate(String d) {
    String result = null;
    Date dateObject = null;
    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy");
    try {
        dateObject = dateFormatter.parse(d);
        dateFormatter.applyPattern("yyyy-MM-dd");
        result = dateFormatter.format(dateObject);

    } catch (ParseException e) {
        System.out.println(e);
    }

    return result;

}
like image 796
Asalas77 Avatar asked Nov 29 '14 15:11

Asalas77


People also ask

What is date format DD MMM YYYY?

DD/MMM/YYYY. Two-digit day, separator, three-letter abbreviation of the month, separator, four-digit year (example: 25/JUL/2003) MMM/DD/YYYY. Three-letter abbreviation of the month, separator, two-digit day, separator, four-digit year (example: JUL/25/2003)

How do you parse a date?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.


1 Answers

Did you try

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");

instead of

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy");

(note the hyphens, since your pattern doesn't match your input)

Also helpful: using Locale.US as recommended by @ZouZou

like image 75
Daniel Alder Avatar answered Sep 18 '22 15:09

Daniel Alder