I am getting a date in this format:
2011-05-23 6:05:00
How can I obtain only 2011-05-23 from this string?
You could just take the index of the first space and use substring:
int firstSpace = text.indexOf(' ');
if (firstSpace != -1)
{
String truncated = text.substring(0, firstSpace);
// Use the truncated version
}
You'd need to work out what you wanted to do if there weren't any spaces.
However, if it's meant to be a valid date/time in a particular format and you know the format, I would parse it in that format, and then only use the date component. Joda Time makes it very easy to take just the date part - as well as being a generally better API.
EDIT: If you mean you've already got a Date object and you're trying to format it in a particular way, then SimpleDateFormat is your friend in the Java API - but again, I'd recommend using Joda Time and its DateTimeFormatter class:
DateTimeFormatter formatter = ISODateTimeFormat.date();
String text = formatter.print(date);
Using SimpleDateFormat:
parser = new SimpleDateFormat("yyyy-MM-dd k:m:s", locale);
Date date;
try {
date = (Date)parser.parse("2011-05-23 6:05:00");
} catch (ParseException e) {
}
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
Also:
Standard way would be use of SimpleDateFormat
You can also accomplish it using String operation as follows
String result = str.substring(0,str.indexOf(" "));
Here you go:
import java.*;
import java.util.*;
import java.text.*;
public class StringApp {
public static void main(String[] args)
{
String oldDate = "2011-05-23 6:05:00";
String dateFormat = "yyyy-MM-dd";
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar cl = Calendar.getInstance();
cl.setTime(sdf.parse(oldDate));
String newDate = sdf.format(cl.getTime());
System.out.println(newDate);
}
catch (ParseException ex) {
}
}
}