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

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

问题描述

我的 json 响应包含一个 CreatedOn 日期:

My json respons contains a CreatedOn Date:

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

我需要将 CreatedOn 转换为简单的日期格式,并计算从 CreatedOn 日期到当前日期的差异天数.

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.

您还应该确保首先尝试 {} catch {} 字符串,以确保其有效的 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天全站免登陆