0

I am trying to add spaces to a string so that I can use it for SimpleDateFormat. I would need to add spaces to this:

String str = "Wed 3Jun15 03:22:15 pm"

I know how to put it into SimpleDateFormat as soon as I get it into this format:

String str = "Wed 3 Jun 15 03:22:15 pm"

Eventually I am only trying to pull d, HH:mm out of this date, so the rest can be trashed.

I have looked at this link: How to split a string between letters and digits (or between digits and letters)? and while it is closed, it doesn't work for what I am trying to do.

Community
  • 1
  • 1
Christopher
  • 53
  • 1
  • 6

1 Answers1

2

This pattern should match your string:

EEE dMMMyy hh:mm:ss a

With your example:

String str = "Wed 3Jun15 03:22:15 pm";
SimpleDateFormat fmt = new SimpleDateFormat("EEE ddMMMyy hh:mm:ss a");
Date d = fmt.parse(str);
SimpleDateFormat output = new SimpleDateFormat("d, HH:mm");
System.out.println(output.format(d)); //prints 3, 15:22
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Worked like a charm. I knew it had to do with the string matching, but I just couldn't seem to get it right. Thanks! Only issue is that, the `fmt.parse(str)` line requires you to throw an exception, which is easy enough to do. Thanks!! – Christopher Jun 10 '15 at 14:33
  • minor follow-up question, this wouldn't work if the date went to double digits, for example `String str = "Wed 22Jun15 03:22:15 pm"` how would you counter for that? Youd have to make some sort of case statement for both, right? @assylias – Christopher Jun 10 '15 at 15:14
  • Mmmm you are right I didn't think of that... See my edit (using `ddMMMyy` instead of `dMMMyy`). – assylias Jun 10 '15 at 15:21
  • yeah, i was just about to say that changing it to `..dd..` works. Thanks. – Christopher Jun 10 '15 at 15:22