Reputation:
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?
Upvotes: 2
Views: 2025
Reputation: 4087
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) {
}
}
}
Upvotes: 0
Reputation: 533890
Another answer which uses a regex.
String dateTime = "2011-05-23 6:05:00";
String date = dateTime.split(" ")[0];
Upvotes: 0
Reputation: 1649
You can use -
String arg="2011-05-23 6:05:00";
String str=arg.substring(0,arg.indexOf(" "));
Upvotes: 1
Reputation: 10959
Lots of answers, but no one had used regexp so far, so I just had to post an answer with regexp.
String date = "2011-05-23 6:05:00";
System.out.println(date.replaceFirst("\\s.*", ""));
Upvotes: 0
Reputation: 332791
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:
Upvotes: 4
Reputation: 7044
Simplest way :
String str="2011-05-23 6:05:00"; str =str.subString(0,10);
Upvotes: 0
Reputation: 3055
str = "2011-05-23 6:05:00"
str = str.substring(0,str.indexOf(" "));
Upvotes: 0
Reputation: 305
Well an ineffective, but brute force method would be to say
String s = "2011-05-23 6:05:00";
String t = s.substring(0,s.length-7);
Or whatever the case should be
Upvotes: 0
Reputation: 240996
Standard way would be use of SimpleDateFormat
You can also accomplish it using String
operation as follows
String result = str.substring(0,str.indexOf(" "));
Upvotes: 1
Reputation: 1504092
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);
Upvotes: 6