【问题标题】:Parsing json date to specific date format将 json 日期解析为特定日期格式
【发布时间】:2019-06-24 11:38:01
【问题描述】:

我试图解析一些包含日期条目作为纪元数值的 json 文档,使用后: Document.parse(((JSONObject) o).toJSONString()) 日期格式自动设置为 ie。 Wed Nov 08 05:10:20 CET 2017 我需要不同的格式(也需要毫秒)

所以问题是,如何解析 ie。 "$date" -> "1510114220518" 到一些带有 Bson Document.parse 方法的自定义格式化字符串?

JSONArray arrJson = getJsonData(sFilePath);
            for (Object o : arrJson) { 
                Document doc = Document.parse(((JSONObject) o).toJSONString());

编辑: 只是一个更新:问题出在 Document.parse 方法中,因为我不知道如何告诉 .parse 函数在解析 json 文档时使用自定义日期格式。我总是得到某种默认日期格式。 如何向 .parse 方法发送一些参数以返回包含所有数据和自定义日期格式的文档? 喜欢:

Format dateFormat = 'yyyy-MM-dd@HH:mm:ss.SSSZ'
Document doc = Document.parse(((JSONObject) o).toJSONString(dateFormat ));```

Im always getting ```Wed Nov 08 05:10:20 CET 2017``` format, **I need a Document with all data and all dates to be in yyyy-MM-dd@HH:mm:ss.SSSZ format** ?

This is sample of json document:
[
{ "_id" : { "user_id" : { "$oid" : "51b76b7459a273c8a6000ed8" }, "updated_at" : { "$date" : 1510114220518 } }, "count" : 153 },
{ "_id" : { "user_id" : { "$oid" : "51b76b7459a273c8a6000ed8" }, "updated_at" : { "$date" : 1511405948977 } }, "count" : 3 },
{ "_id" : { "user_id" : { "$oid" : "51b76b7459a273c8a6000ed8" }, "updated_at" : { "$date" : 1511405948991 } }, "count" : 153 }

and when I do the Document.parse()...date is in some default format like ie. Wed Nov 08 05:10:20 CET 2017

【问题讨论】:

标签: java json date parsing


【解决方案1】:

据我了解您的问题,您可以使用 Java 的 SimpleDateFormat 类。例如:

long time = 1510114220518;
SimpleDateFormat simpleFormat = new SimpleDateFormat ("yyyy.MM.dd 'at' hh:mm:ss");
Date date = new Date(time);
System.out.println(simpleFormat.format(date));

【讨论】:

  • 感谢您的贡献。请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。
  • @OleV.V.谢谢你的提示!我不知道它已经过时了,因为仍然有很多指南指向这个类。很高兴学习新东西!
  • 没错,不幸的是,很多展示如何使用这些旧类的页面仍然存在。
  • Tnx 伙计们响应,但恐怕我没有很好地解释你的情况,我知道当我直接使用日期变量时如何使用日期格式,但在这种情况下我没有选择,因为我无法影响 bson Document.parse() ..它只是解析我的 json 对象并返回一个我无法接受的日期格式的字符串。请查看帖子更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多