How to parse .net DateTime received as json string into java's Date object

后端 未结 5 2205
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 22:57

I\'m receiving .NET\'s DateTime object as json string through my asmx webservice and trying to parse it with help of gson library. But seems like there\'s no su

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 23:39

    To manually convert a .NET JSON date to a JodaTime DateTime object (native Java type similar), you can also use a regex:

    public static DateTime parseDotNetTime(String json) {
        DateTime result = null;
        if (json != null) {
            Pattern datePatt = Pattern.compile("^/Date\\((\\d+)([+-]\\d+)?\\)/$");
            Matcher m = datePatt.matcher(json);
            if (m.matches()) {
                Long l = Long.parseLong(m.group(1));
                result = new DateTime(l);
                // Time zone is not needed to calculate date
            } else {
                throw new IllegalArgumentException("Wrong date format");
            }
        }
        return result;
    }
    

提交回复
热议问题