17

I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"

I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.

1
  • 1
    Have a look at codingbat - it provides a lot of short exercises to get used to the language :) Commented Feb 14, 2012 at 12:18

12 Answers 12

41

Four options (last two added to make this one answer include the options given by others):

  • Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)
  • Find the first space using indexOf and get the leading substring using substring:

    int spaceIndex = text.indexOf(" ");
    if (spaceIndex != -1)
    {
        text = text.substring(0, spaceIndex);
    }
    
  • Trust that it's valid in the specified format, and that the first space will always be at index 10:

    text = text.substring(0, 10);
    
  • Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)

    text = text.split(" ")[0];
    

You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.

Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?

Sign up to request clarification or add additional context in comments.

3 Comments

text.substring(0, spaceIndex+1);
@Ademiban: Why would the OP want to keep the space at the end? That seems unlikely to me.
text = text.split(" ", 2)[0]; <== is faster
13
String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];

Comments

7

Try this:

String date = s.substring(0, s.indexOf(" "));

Or even (because the length is fixed):

String date = s.substring(0, 10);

Or use StringUtils.substringBefore():

String date = StringUtils.substringBefore(s, " ");

1 Comment

@Ademiban: nope, looks like my version (without +1) is correct, I guess we don't need the trailing space after date.
2

Lots of ways to do this, a very simple method is to split the String at the space and use the first part (which will be the date):

String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];

Comments

1

You can use String.split() and take only the relevant String in your resultng String[] [in your example, it will be myString.split(" ")[0]

Comments

1

In that case where only one space is in the string, you can use String.split(" "). But this is a bad practice. You should parse the date with a DateFormat .

Comments

1

You can use substring to extract the date only:

 String thedatetime = "01-01-2012 01:01:01";
 String thedateonly = thedate.substring(0, 10);

You should really read through the javadoc for String so you are aware of the available functions.

Comments

1

If you know in advance this is the format of the string, I'd do this:

public String getDateOnly(String fullDate){
    String[] spl = fullDate.split(" ");
    return spl[0];
} 

Comments

1

You can do it either using string manipulation API:

String datetime =  "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
   String date = datetime.substring(0, spacePos - 1);
}

or using regular expression:

Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime =  "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
   String date = m.group(1);
}

or using SimpleDateFormat

DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();

Comments

0

Use String.substring(int, int). If you are interested in the value of the date and time, then use SimpleDateFormatter to parse your string.

Comments

0

myString.substring(0,10);

If your string is always in that format (2 digits, minus, 2 digits, minus, 4 digits, space etc...) then you can use substring(int beginIndex, int endIndex) method of string to get what you want.
Note that second parameter is the index of character after returning substring.

Comments

0

If you want to explode the complete date from the string use this method.

/**
 * @param dateTime format string
 * @param type type of return value : "date" or "time"
 * @return String value
 */

private String getFullDate(String dateTime, String type) {
    String[] array = dateTime.split(" ");
    if (type == "time") {
        System.out.println("getDate: TIME: " + array[1]);
        return array[1];

    } else if (type == "date") {
        System.out.println("getDate: DATE: " + array[0]);
        return array[0];
    } else {
        System.out.println("NULL.");
        return null;
    }
}

Otherwise if you want only the date for explample 01-01-2012

use this:

/**
 * @param datetime format string
 * @return
 */
private String getOnlyDate(String datetime) {
    String array[] = datetime.split("-");
    System.out.println("getDate: DATE: " + array[0]);

    return array[0];

}

I hope my answer will help you.

1 Comment

Please explain why your solutions works and also provide comments for better understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.