将 Json 日期转换为 Java 日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24956396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Json date to java date
提问by SreeAndroidDev
My json respons contains a CreatedOnDate:
我的 json响应包含一个CreatedOn日期:
{
"CreatedOn" : "\/Date(1406192939581)\/"
}
I need to convert CreatedOnto a simple date format and count the days of difference from CreatedOn Date to Present Date.
我需要将CreatedOn转换为简单的日期格式,并计算从 CreatedOn 日期到当前日期的差异天数。
When I debug the below code string CreatedOnshowing a null value. How come?
当我调试下面显示空值的代码字符串CreatedOn 时。怎么来的?
JSONObject store = new JSONObject(response);
if (response.contains("CreatedOn"))
{
String CreatedOn = store.getString("CreatedOn");
}
采纳答案by Emanuel S
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);
}
or
或者
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);
}
consider using JSON methods instead of contains. JSON has "has()" which validate if key exists.
考虑使用 JSON 方法而不是包含。JSON 具有“has()”,用于验证密钥是否存在。
You should also make sure that you try {} catch {} the String first, to make sure its valid JSON.
您还应该确保首先尝试 {} catch {} 字符串,以确保其有效的 JSON。
Update:
更新:
Your Value is /Date(1406192939581)/
您的值是 /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", ""));
回答by Ole V.V.
java.time
时间
It's about time that someone provides the modern answer. When this question was asked in 2014, Java 8 had just come out, and with it java.time, the modern Java date and time API. Today I recommend we all use this and avoid the old classes Timestamp
, Date
, DateFormat
and SimpleDateFormat
used in the other answer. The old classes were poorly designed and were replaced for a good reason.
是时候有人提供现代答案了。当这个问题在 2014 年被问到时,Java 8 刚刚问世,随之而来的是 java.time,现代 Java 日期和时间 API。今天我建议我们都使用这个并避免使用旧的类Timestamp
, Date
,DateFormat
和SimpleDateFormat
在另一个答案中使用。旧类的设计很差,被替换是有充分理由的。
Edit:With Java 8 you can directly parse your string from JSON into an Instant
using an advanced formatter, which I consider quite elegant:
编辑:使用 Java 8,您可以Instant
使用高级格式化程序直接将字符串从 JSON 解析为一个,我认为这非常优雅:
DateTimeFormatter jsonDateFormatter = new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendLiteral(")/")
.toFormatter();
String createdOn = "/Date(1406192939581)/";
Instant created = jsonDateFormatter.parse(createdOn, Instant::from);
System.out.println("Created on " + created);
Output from this snippet is:
此代码段的输出是:
Created on 2014-07-24T09:08:59.581Z
创建于 2014-07-24T09:08:59.581Z
The formatter knows that the last 3 digits are milliseconds of the second and considers all the preceding digits seconds since the epoch, so this works the way it should. To count the days of difference from CreatedOn Date to Present Date:
格式化程序知道最后 3 位数字是秒的毫秒数,并考虑了自纪元以来所有前面的数字秒,所以这应该以它应该的方式工作。要计算从 CreatedOn Date 到 Present Date 的差异天数:
ZoneId zone = ZoneId.of("Antarctica/South_Pole");
long days = ChronoUnit.DAYS.between(created.atZone(zone).toLocalDate(), LocalDate.now(zone));
System.out.println("Days of difference: " + days);
Output today (2019-12-20):
今天的输出(2019-12-20):
Days of difference: 1975
天差:1975
Please substitute your desired time zone if it didn't happen to be Antarctica/South_Pole.
如果它不是南极洲/南极洲,请替换您想要的时区。
Original answer:
原答案:
final Pattern jsonDatePattern = Pattern.compile("/Date\((\d+)\)/");
String createdOn = "/Date(1406192939581)/";
Matcher dateMatcher = jsonDatePattern.matcher(createdOn);
if (dateMatcher.matches()) {
Instant created = Instant.ofEpochMilli(Long.parseLong(dateMatcher.group(1)));
System.out.println("Created on " + created);
} else {
System.err.println("Invalid format: " + createdOn);
}
Output is:
输出是:
Created on 2014-07-24T09:08:59.581Z
创建于 2014-07-24T09:08:59.581Z
I am using a regular expression not only to extract the number from the string, but also for validation of the string.
我使用正则表达式不仅从字符串中提取数字,还用于验证字符串。
The modern Instant
class represents a point in time. It's toString
method renders the time in UTC, so this is what you see in the output, denoted by the trailing Z
.
现代Instant
阶级代表了一个时间点。它的toString
方法以 UTC 时间呈现时间,因此这就是您在输出中看到的内容,由尾随Z
.
Link:Oracle tutorial: Date Timeexplaining how to use java.time.
链接:Oracle 教程:解释如何使用 java.time 的日期时间。