将Json日期转换为java日期 [英] Convert Json date to java date

查看:149
本文介绍了将Json日期转换为java日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json回复包含一个 CreatedOn 日期:

My json respons contains a CreatedOn Date:

{
"CreatedOn" : "\/Date(1406192939581)\/"
}

我需要将 CreatedOn 转换为简单的日期格式,并将计数与CreatedOn Date到当前日期的差异日期。

I need to convert CreatedOn to a simple date format and count the days of difference from CreatedOn Date to Present Date.

我调试下面的代码字符串 CreatedOn 显示一个空值。如何来?

When I debug the below code string CreatedOn showing a null value. How come?

JSONObject store = new JSONObject(response);

if (response.contains("CreatedOn"))
{
    String CreatedOn = store.getString("CreatedOn");
}   


推荐答案

JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
  Timestamp stamp = new Timestamp(store.getLong("CreatedOn"));
  Date date = new Date(stamp.getTime());
  System.out.println(date);
}

JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
 Date date = new Date(datetimestamp);
 DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
 String dateFormatted = formatter.format(date);
}

考虑使用JSON方法而不是包含。 JSON有has(),如果键存在,则验证。

consider using JSON methods instead of contains. JSON has "has()" which validate if key exists.

您还应确保尝试{}首先捕获{}该String,以确保其有效JSON。

You should also make sure that you try {} catch {} the String first, to make sure its valid JSON.

更新:

您的价值是
/日期(1406192939581)/

Your Value is /Date(1406192939581)/

这意味着它必须先被格式化。
通过使用

which means it must be formatted first. Get it by parsing the string with

Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));

这篇关于将Json日期转换为java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆