Sre*_*Dev 1 java datetime json gson
我的 json响应包含一个CreatedOn日期:
{
"CreatedOn" : "\/Date(1406192939581)\/"
}
Run Code Online (Sandbox Code Playgroud)
我需要将CreatedOn转换为简单的日期格式,并计算从 CreatedOn 日期到当前日期的差异天数。
当我调试下面显示空值的代码字符串CreatedOn 时。怎么来的?
JSONObject store = new JSONObject(response);
if (response.contains("CreatedOn"))
{
String CreatedOn = store.getString("CreatedOn");
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
或者
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);
}
Run Code Online (Sandbox Code Playgroud)
考虑使用 JSON 方法而不是包含。JSON 具有“has()”,用于验证密钥是否存在。
您还应该确保首先尝试 {} catch {} 字符串,以确保其有效的 JSON。
更新:
您的值是 /Date(1406192939581)/
这意味着它必须先格式化。通过解析字符串来获取它
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16881 次 |
| 最近记录: |