Search code examples
javasplitzoneddatetime

How can I parse string using square brackets as a delimiter in Java?


I have a class that parses ZonedDateTime objects using.split() to get rid of all the extra information I don't want.

My Question: Is there a way to use square brackets as delimiters that I am missing, OR how do I get the time zone ([US/Mountain]) by itself without using square brackets as delimiters?

I want the String timeZone to look like "US/Mountian" or "[US/Mountian]

What I've Tried: Ive tried wholeThing.split("[[-T:.]]?) and wholeThing.split("[%[-T:.%]]") but those both give me 00[US/Mountain]

I've also tried wholeThing.split("[\\[-T:.\\]]) and wholeThing.split("[\[-T:.\]") but those just give me errors.

(part of) My Code:

 //We start out with something like   2016-09-28T17:38:38.990-06:00[US/Mountain]

    String[] whatTimeIsIt = wholeThing.split("[[-T:.]]"); //wholeThing is a TimeDateZone object converted to a String
    String year = whatTimeIsIt[0];
    String month = setMonth(whatTimeIsIt[1]);
    String day = whatTimeIsIt[2];
    String hour = setHour(whatTimeIsIt[3]);
    String minute = whatTimeIsIt[4];
    String second = setAmPm(whatTimeIsIt[5],whatTimeIsIt[3]);
    String timeZone = whatTimeIsIt[8];

Solution

  • Using split() is the right idea.

    String[] timeZoneTemp = wholeThing.split("\\[");
    String timeZone = timeZoneTemp[1].substring(0, timeZoneTemp[1].length() - 1);