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?
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
than any solution relying on splitting strings, substrings on fixed indexes or regular expressions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With