How to get Date part from given String?

date-parsing, java

Solution

The proper way to do it is to parse it into a `Date` object and format this date object the way you want.

DateFormat inputDF  = new SimpleDateFormat("EEE, d MMM yyyy H:m:s z");
DateFormat outputDF = new SimpleDateFormat("d MMM yyyy");

String input = "Mon, 14 May 2012 13:56:38 GMT";
Date date = inputDF.parse(input);
String output = outputDF.format(date);

System.out.println(output);

Output:

14 May 2012

This code is

- easier to maintain (what if the output format changes slightly, while the input format is preserved? or vice versa?)

- arguably easier to read

than any solution relying on splitting strings, substrings on fixed indexes or regular expressions.

Problem

I have string like this: `Mon, 14 May 2012 13:56:38 GMT` Now I just want only date i.e. `14 May 2012` What should I need to do for that?

Original source