Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Date part from given String?

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?

like image 557
Neha Avatar asked Dec 16 '22 00:12

Neha


2 Answers

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.

like image 96
aioobe Avatar answered Jan 03 '23 06:01

aioobe


Why don't you parse() the String using DateFormat, which will give you a Date object. Give this Date to a Calendar, and you can query any of the fields that you want, such as get(Calendar.DAY_OF_MONTH).

Something like this...

SimpleDateFormat myDateFormat = new SimpleDateFormat("EEE, d MMM yyyy H:m:s z");
Date myDate = myDateFormat.parse(inputString);

Calendar myCalendar = Calendar.getInstance();
myCalendar.setTime(myDate);

String outputDate = myCalendar.get(Calendar.DAY_OF_MONTH) + " " + 
                    myCalendar.get(Calendar.MONTH) + " " +
                    myCalendar.get(Calendar.YEAR);

Might be a little bit lengthy to write, but at least you end up with a Calendar that can easily give you any field you want (if, for example, you want to perform some processing using one of the field values). It can also be used for calculations, or many other purposes. It really depends on what you want to do with the date after you have it.

like image 44
wattostudios Avatar answered Jan 03 '23 04:01

wattostudios