转换JSON日期格式 [英] Convert JSON date format
问题描述
我收到一个日期值如下的JSON对象:
I'm receiving a JSON object with date value like this:
{"PostingDate":"\/Date(1325134800000-0500)\/"}
我想用Java代码解析它日期
或将其作为字符串
。
And I want to parse it in Java code to Date
or getting it as a String
.
我想要要知道这样做的简单方法。
I want to know what is the easy way of doing it.
推荐答案
我把它作为第一个数字( 1325134800000
)是自纪元以来的毫秒数, -0500
是时区。这似乎是下面的示例代码的情况,它似乎做你想要的。
I take it the first number (1325134800000
) is the number of milliseconds since epoch, and -0500
is the time zone. This appears to be the case given the sample code below, which seems to do what you want.
以下代码使用 Jackson ,如果您还没有选择JSON解析库,我建议您这样做。它没有错误检查等。
The following code parses the JSON input using Jackson, which I recommend if you don't have a JSON parsing library of choice yet. It lacks error checking etc.
示例代码:
public final class Foo
{
public static void main(final String... args)
throws IOException
{
// What the JSON value must match exactly
// Not anchored since it will be used with the (misnamed) .matches() method
final Pattern pattern
= Pattern.compile("\\\\/Date\\((\\d+)(-\\d+)?\\)\\\\/");
final ObjectMapper mapper = new ObjectMapper();
// Parse JSON...
final JsonNode node = mapper.readTree(
"{\"PostingDate\": \"\\/Date(1325134800000-0500)\\/\"}");
if (!node.has("PostingDate")) {
System.err.println("Bad JSON input!");
System.exit(1);
}
// Get relevant field
final String dateSpec = node.get("PostingDate").getTextValue();
// Try and match the input.
final Matcher matcher = pattern.matcher(dateSpec);
if (!matcher.matches()) {
System.err.println("Bad pattern!"); // Yuck
System.exit(1);
}
// The first group capture the milliseconds, the second one the time zone
final long millis = Long.parseLong(matcher.group(1));
String tz = matcher.group(2);
if (tz.isEmpty()) // It can happen, in which case the default is assumed to be...
tz = "+0000";
// Instantiate a date object...
final Date date = new Date(millis);
// And print it using an appropriate date format
System.out.printf("Date: %s %s\n",
new SimpleDateFormat("yyyy/MM/dd HH:MM:ss").format(date), tz);
}
}
输出:
Date: 2011/12/29 06:12:00 -0500
这篇关于转换JSON日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!