问题
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?
回答1:
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.
回答2:
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.
回答3:
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();
来源:https://stackoverflow.com/questions/10601321/how-to-get-date-part-from-given-string