Reputation: 75
I have a long string dates that I receive from an API call and they are returned as
Event Name 2017-03-23T10:00.000+01:00
How do I trim it so that I can remove the characters from all of the events that I get back and be left with only
Event Name 2017-03-23 10:00
Upvotes: 1
Views: 10981
Reputation: 3629
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
Change x
with your last character.
Upvotes: 0
Reputation: 590
StringBuilder sb = new StringBuilder("Event Name 2017-03-23T10:00.000+01:00");
sb.setLength(27);
System.out.println(sb.toString());
Upvotes: 0
Reputation: 56393
How do I trim it so that I can remove the characters from all of the events that I get back and be left with only
Event Name 2017-03-23 10:00
Try this:
String str = "Event Name 2017-03-23T10:00.000+01:00";
String newString = str.replace("T"," ");
System.out.println(newString.substring(0, newString.lastIndexOf(".")));
result is --> Event Name 2017-03-23 10:00
side note - as you can see working with Strings
is a bit inefficient in terms of constructing a new object each time, you may consider looking into StringBuilder. However, if you're doing no more operations then I've already done then that should be fine.
EDIT
Alternative solution
String str = "Event Name 2017-03-23T10:00.000+01:00";
System.out.println(str.split("\\.")[0]);
Note - this is similar to the solution above but leaves the "T" where it currently is. you can then go on further and do what you wish to do with it.
Upvotes: 3