Search code examples
javajsondatetimeodata

convert Json Date with Offset to java date


I have a Json date with offset. I need to convert that to java.

Edm.DateTime

"/Date(<ticks>["+" | "-" <offset>)/"

<ticks> = number of milliseconds since midnight Jan 1, 1970

<offset> = number of minutes to add or subtract

Using this answer copied below, I am able to convert this date to Java. However, this does not takes into consideration the offset component. Is there any simpler way of resolving the offset.

Date date = new Date(Long.parseLong(jsonDate.replaceAll(".*?(\\d+).*", "$1")));

Below are some String dates that I am getting in the json date format

/Date(1463667774000+0400)/

/Date(1463667774000-5300)/

Program and result below

   str = "/Date(1463667774000-9000)/";
     date = new Date(Long.parseLong(str.replaceAll(".*?(\\d+).*", "$1")));
     System.out.println("1st "+ date);

      1st Thu May 19 19:52:54 IST 2016

Can somebody please help?


Solution

  • Here's an example on how to parse your custom dates.

    // test value
    String[] jsonDates = {"/Date(1463667774000-9000)/","/Date(1463667774000)/", "/Date(1463667774000+0400)/"};
    //                          | preceded by "("
    //                          |       | group 1: timestamp
    //                          |       |    | optional group 2: "+" or "-"
    //                          |       |    |      | optional group 3
    //                          |       |    |      | (within group 2):    
    //                          |       |    |      | minutes
    //                          |       |    |      |       | followed by ")"
    Pattern p = Pattern.compile("(?<=\\()(\\d+)(([-+])(\\d+))?(?=\\))");
    for (String jsonDate: jsonDates) {
        Matcher m = p.matcher(jsonDate);
        // matching pattern...
        if (m.find()) {
            // found: parsing timstamp
            long timestamp = Long.parseLong(m.group(1));
            Integer minutes = null;
            Boolean addOrSubstract = null;
            if (m.group(2) != null) {
                // parsing sign
                addOrSubstract = "+".equals(m.group(3)); 
                // parsing minutes
                if (m.group(4) != null) {
                    minutes = Integer.parseInt(m.group(4));
                }
            }
    
            // initializing calendar
            Calendar c = Calendar.getInstance();
            c.setTime(new Date(timestamp));
            // adding/removing minutes if parsed
            if (minutes != null) {
                c.add(
                    Calendar.MINUTE, 
                    addOrSubstract != null ? 
                    (addOrSubstract ? minutes : -minutes) : 0
                );
            }
            Date date = c.getTime();
            System.out.println(date);
        }
        // not matched, different format
        else {
            // TODO error
        }
    }