Zack Andrews
Zack Andrews

Reputation: 13

Java String split not working as expected using a colon (":")

I am trying to remove the seconds off of this string:

10/31/2009 9:46:16 AM

I'm attempting using the following function to do this:

public static String correctValue4(String str) {
    String parts[] = str.split(":");
    String fixedStr = parts[0] + ":" + parts[1];
    return fixedStr;
}

I figured it would parse through it and get the 10/31/2009 9 and then add the 46 at the end. However, I am getting a "java.lang.ArrayIndexOutOfBoundsException: 1" error upon running. Obviously, it's not picking up the parts[1].

Any ideas?

For extra karma: I'm needing to append the AM/PM back onto the end of the string. So, in the end it should look like this:

10/31/2009 9:46 AM

Thanks, your help is greatly appreciated =)

EDIT:

Sorry, I should have been more specific regarding the date. What I'm doing is accepting a tab delimited text file into the application and then formatting it and outputting it into a new file. All I was needing to do was drop the seconds from the date as per request and output it; I think I was just way over complicating it.

Tim's answer worked in this case!

Thank you, everyone, who offered suggestions!

Upvotes: 1

Views: 3908

Answers (4)

Robin
Robin

Reputation: 36611

If the String is always of the same format (ending in 2 digits for the seconds, a space and them AM or PM), you can just extract the relevant parts with the substring method available on each String instance

String original = "10/31/2009 9:46:16 AM";
//-6 since we want to remove the : as well
String firstPart = original.substring( 0, original.length() - 6 );
String secondPart = original.substring( original.length() - 3, original.length() );
String result = firstPart + secondPart;

Upvotes: 1

Alexis Pigeon
Alexis Pigeon

Reputation: 7512

Why don't you use SimpleDateFormat?

First parse the Date :

Date d = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(str);

Then format the Date :

new SimpleDateFormat("MM/dd/yyyy h:mm a").format(d);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502376

I would advise a different approach entirely: parse the value into the appropriate domain-specific type (I'd use LocalDateTime from Joda Time) and then reformat it in the format you want. This will perform validation at the same time, so you don't propagate bad data through your system just because it happens to have a colon in it.

Joda Time provides parse and format facilities (see DateTimeFormat and DateTimeFormatter), so it should be pretty simple.

Upvotes: 6

Tim Pietzcker
Tim Pietzcker

Reputation: 336408

Couldn't you just remove a colon that's followed by two digits if a space is the next character that follows?

String resultString = subjectString.replaceAll(":\\d{2}(?= )", "");

Upvotes: 1

Related Questions