栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

转换JSON日期格式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

转换JSON日期格式

我认为第一个数字(

1325134800000
)是自纪元以来的毫秒数,并且
-0500
是时区。鉴于以下示例代码似乎是这种情况,它似乎可以满足您的要求。

以下代码使用Jackson解析JSON输入,如果您还没有选择的JSON解析库,我建议您这样做。它缺少错误检查等。

样例代码:

public final class Foo{    public static void main(final String... args)        throws IOException    {        // What the JSON value must match exactly        // Not anchored since it will be used with the (misnamed) .matches() method        final Pattern pattern = Pattern.compile("\\/Date\((\d+)(-\d+)?\)\\/");        final ObjectMapper mapper = new ObjectMapper();        // Parse JSON...        final JsonNode node = mapper.readTree( "{"PostingDate": "\/Date(1325134800000-0500)\/"}");        if (!node.has("PostingDate")) { System.err.println("Bad JSON input!"); System.exit(1);        }        // Get relevant field        final String dateSpec = node.get("PostingDate").getTextValue();        // Try and match the input.        final Matcher matcher = pattern.matcher(dateSpec);        if (!matcher.matches()) { System.err.println("Bad pattern!"); // Yuck System.exit(1);        }        // The first group capture the milliseconds, the second one the time zone        final long millis = Long.parseLong(matcher.group(1));        String tz = matcher.group(2);        if (tz.isEmpty()) // It can happen, in which case the default is assumed to be... tz = "+0000";        // Instantiate a date object... final Date date = new Date(millis);        // And print it using an appropriate date format        System.out.printf("Date: %s %sn", new SimpleDateFormat("yyyy/MM/dd HH:MM:ss").format(date), tz);    }}

输出:

Date: 2011/12/29 06:12:00 -0500


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/398146.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号