问题描述
我在这里仔细检查了所有可能的答案,但是我很难弄清这个问题。
I looked through all possible answer here but I am having hard time to figure this thing out.
我在字符串中有Json日期。我想转换成Java Date而不浪费时间。
I have Json date in a String. I want to convert into a Java Date without losing time.
我也想从Java Date转换为Json Date字符串。
Also I would like to convert from Java Date to Json Date string.
这里是我所拥有的。
String jsonDateString = "/Date(1295157600000-0600)/";
推荐答案
您的时间有两部分:当地时间以毫秒为单位,偏移量以小时和分钟为单位。您必须解析它们并添加它们以获得毫秒级的UTC。
There are 2 parts in your time : the local time in milliseconds, and the offset in hours and minutes. You have to parse them and "add" them to get the milliseconds UTC.
您可以使用以下功能:
private static Pattern p = Pattern.compile("\\((\\d+)([+-]\\d{2})(\\d{2})\\)");
public static Date jd2d(String jsonDateString) {
Matcher m = p.matcher(jsonDateString);
if (m.find()) {
long millis = Long.parseLong(m.group(1));
long offsetHours = Long.parseLong(m.group(2));
long offsetMinutes = Long.parseLong(m.group(3));
if (offsetHours<0) offsetMinutes *= -1;
return new Date(
millis
+ offsetHours*60l*60l*1000l
+ offsetMinutes*60l*1000l
);
}
return null;
}
要返回 JSON日期,我只需对UTC时间进行编码:
To make "back" a JSON date, I would simply encode the UTC time :
String jsonDate = "/Date("+date.getTime()+"+0000)/";
这篇关于将Json Date转换为Java Date并返回至Json Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!