2016-07-15 57 views
1

我有一個帶偏移量的Json日期。我需要將其轉換爲java。將Json日期與偏移量轉換爲java日期

Edm.DateTime

"/Date(<ticks>["+" | "-" <offset>)/" 

<ticks> = number of milliseconds since midnight Jan 1, 1970 

<offset> = number of minutes to add or subtract 

使用這種answer下面複製,我能夠在此日期轉換成Java。但是,這不考慮偏移量分量。有沒有更簡單的方法來解決偏移量問題。

Date date = new Date(Long.parseLong(jsonDate.replaceAll(".*?(\\d+).*", "$1"))); 

下面是我在JSON日期格式我得到一些字符串日期

/日期(1463667774000 + 0400)/

/日期(1463667774000-5300)/

計劃並導致下面

str = "/Date(1463667774000-9000)/"; 
    date = new Date(Long.parseLong(str.replaceAll(".*?(\\d+).*", "$1"))); 
    System.out.println("1st "+ date); 

     1st Thu May 19 19:52:54 IST 2016 

可有人請幫忙嗎?

+0

你可以發佈你在JSON中的實際日期值的幾個例子嗎? – Mena

+0

@Mena:我已經更新了我的問題。請檢查 – mattymanme

回答

1

下面是關於如何解析自定義日期的示例。

// test value 
String[] jsonDates = {"/Date(1463667774000-9000)/","/Date(1463667774000)/", "/Date(1463667774000+0400)/"}; 
//       | preceded by "(" 
//       |  | group 1: timestamp 
//       |  | | optional group 2: "+" or "-" 
//       |  | |  | optional group 3 
//       |  | |  | (within group 2):  
//       |  | |  | minutes 
//       |  | |  |  | followed by ")" 
Pattern p = Pattern.compile("(?<=\\()(\\d+)(([-+])(\\d+))?(?=\\))"); 
for (String jsonDate: jsonDates) { 
    Matcher m = p.matcher(jsonDate); 
    // matching pattern... 
    if (m.find()) { 
     // found: parsing timstamp 
     long timestamp = Long.parseLong(m.group(1)); 
     Integer minutes = null; 
     Boolean addOrSubstract = null; 
     if (m.group(2) != null) { 
      // parsing sign 
      addOrSubstract = "+".equals(m.group(3)); 
      // parsing minutes 
      if (m.group(4) != null) { 
       minutes = Integer.parseInt(m.group(4)); 
      } 
     } 

     // initializing calendar 
     Calendar c = Calendar.getInstance(); 
     c.setTime(new Date(timestamp)); 
     // adding/removing minutes if parsed 
     if (minutes != null) { 
      c.add(
       Calendar.MINUTE, 
       addOrSubstract != null ? 
       (addOrSubstract ? minutes : -minutes) : 0 
      ); 
     } 
     Date date = c.getTime(); 
     System.out.println(date); 
    } 
    // not matched, different format 
    else { 
     // TODO error 
    } 
} 
+0

這不適用於json日期格式的日期'/ Date(1463667774000)/'。我在else部分添加了處理。非常感謝 – mattymanme

+0

@mattymanme更好地處理模式和有條件使用。讓我試着編輯我的答案 – Mena

+0

謝謝。那太好了。 :) – mattymanme