Milos Cuculovic
Milos Cuculovic

Reputation: 20223

How to delete all the characters after one character in the String?

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.

Upvotes: 17

Views: 44826

Answers (12)

Thales Chadiarakos
Thales Chadiarakos

Reputation: 1

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503200

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?

Upvotes: 41

shift66
shift66

Reputation: 11958

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.

Upvotes: 0

AlexR
AlexR

Reputation: 115388

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();

Upvotes: 1

Wilhelm Kleu
Wilhelm Kleu

Reputation: 11077

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];

Upvotes: 2

Gilthans
Gilthans

Reputation: 1726

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];
} 

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103535

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.

Upvotes: 1

Stephan
Stephan

Reputation: 4443

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 .

Upvotes: 1

Guillaume Polet
Guillaume Polet

Reputation: 47627

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

Upvotes: 0

juergen d
juergen d

Reputation: 204894

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

Upvotes: 13

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340953

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, " ");

Upvotes: 7

amit
amit

Reputation: 178521

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

Upvotes: 1

Related Questions