Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove some characters from a String

Tags:

java

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?


2 Answers

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);
like image 141
Jon Skeet Avatar answered Dec 10 '25 01:12

Jon Skeet


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:

  • http://www.exampledepot.com/egs/java.text/FormatDate.html
like image 23
OMG Ponies Avatar answered Dec 10 '25 01:12

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!