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?
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.
The accepted answer uses SimpleDateFormat
which was the correct thing to do in 2012. In Mar 2014, the java.util
date-time API and their formatting API, SimpleDateFormat
were supplanted by the modern Date-Time API. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using the modern date-time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String stdDateTime = "Mon, 14 May 2012 13:56:38 GMT";
ZonedDateTime zdt = ZonedDateTime.parse(stdDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM uuuu", Locale.ENGLISH);
String strDate = zdt.format(formatter);
System.out.println(strDate);
}
}
Output:
14 May 2012
Learn more about the modern Date-Time API from Trail: Date Time.
You can use this:
String st = "Mon, 14 May 2012 13:56:38 GMT";
for(int i=0;i<=st.length();i++){
if (st.charAt(i)==':') {
index=i;
index=index-2;
break;
}
}
String onlyDate=st.substring(4,index).trim();