how to convert incoming Json date into java date format?

前端 未结 2 2008
南旧
南旧 2020-12-21 04:53

I am working on Xero accounts Apis In json response i am getting date like below

 \"Date\": \"/Date(1455447600000+1300)/\",

also same date

相关标签:
2条回答
  • 2020-12-21 05:28

    java.time

    I should like to contribute the modern solution

        Pattern jsonDatePattern = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
        String dateFromJson = "/Date(1455447600000+1300)/";
        Matcher m = jsonDatePattern.matcher(dateFromJson);
        if (m.matches()) {
            long epochMillis = Long.parseLong(m.group(1));
            String offsetString = m.group(2);
            OffsetDateTime dateTime = Instant.ofEpochMilli(epochMillis)
                    .atOffset(ZoneOffset.of(offsetString));
            System.out.println(dateTime);
        }
    

    Output:

    2016-02-15T00:00+13:00

    This agrees with the date and time in your JSON date string and additionally informs you of the UTC offset.

    I am using and warmly recommending java.time, the modern Java date and time API. And discouraging the classes Date, Calendar and TimeZone used in the question and in the other answer. They are long outdated, and the modern Java date and time API is so much nicer to work with.

    Link

    Oracle tutorial: Date Time explaining how to use java.time.

    0 讨论(0)
  • 2020-12-21 05:29

    The +1300 is not a milliseconds offset, it's an hour + minute offset. If you parse just the date part as a long:

    Long longDate=Long.valueOf("1455447600000");
    Date date = new Date(longDate);
    System.out.println(date);
    

    You get (I'm in GMT timezone)

    Sun Feb 14 11:00:00 GMT 2016
    

    And you can see that 11 + 13 = 24, and 24 hours is the next day.

    You can get the timezone from the offset, knowing the offset is 13 hours and zero minutes:

    Calendar c=Calendar.getInstance(TimeZone.getTimeZone(TimeZone.getAvailableIDs(13*3600*1000)[0]));
    c.setTimeInMillis(longDate);
    DateFormat df=DateFormat.getDateInstance();
    df.setTimeZone(c.getTimeZone());
    System.out.println(df.format(c.getTime()));
    

    Which gives me

    Feb 15, 2016
    

    Here so I calculate the offset as being 13 hours, hence 13*3600 seconds, hence 13*3600*1000 milliseconds. So you can parse your string: what's before the plus sign is the time, what's after is the timezone.

    0 讨论(0)
提交回复
热议问题