2012-08-16 85 views
0

我试图将Json日期字符串转换为java日期格式。但是,它涉及到“返回df.parse(tarih)”行时会出错。如何将Json日期转换为Java日期

JSON:

{"DateFrom":"\/Date(1323087840000+0200)\/"} 

Java代码:

private Date JSONTarihConvert(String tarih) throws ParseException 
{ 


    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"); 


    if (tarih.endsWith("Z")) { 
     tarih = tarih.substring(0, tarih.length() - 1) + "GMT-00:00"; 
    } else { 
     int inset = 6; 


     String s0 = tarih.substring(6, tarih.length()-1 - inset); 
     String s1 = tarih.substring(tarih.length()- inset,tarih.length()-2); 

     tarih = s0 + "GMT" + s1; 
    } 


     return df.parse(tarih); 

} 

当我把这种方法,tarih参数为:/日期(1323087840000 + 0200)/

+2

到底是什么错误,可能还发布tarih的例子吗? :) – yoshi 2012-08-16 09:24:49

+0

提供的日期没有任何'-'。然后你在没有'-'的情况下将这个字符串转换成其他的东西。那么你的日期格式不能正确解析它,因为它期望'-'。 – helios 2012-08-16 09:26:34

+0

Tarih是来自土耳其的日期,基本上tari是他试图解析的JSON日期。 – JMelnik 2012-08-16 09:28:31

回答

4

正如您对Date对象感兴趣,并且JSON在我看来是一个unix时间戳。
所以我建议你Date(long milliseconds)构造:)

private Date JSONTarihConvert(String tarih) throws ParseException{ 
    long timestamp = getTimeStampFromTarih(tarih); 
    return new Date(timestamp); 
} 

getTimeStampFromTarih的 “+”

+0

这解决了我的问题,谢谢。 – essbek 2012-08-16 09:43:18

1

除非你有充分的理由不是,您应该使用解析器来序列化和反序列化对象。像Jackson解析器。

1

发生之前提取毫秒这将工作肯定

String date = "/Date(1376841597000)/"; 
Calendar calendar = Calendar.getInstance(); 
String datereip = date.replace("/Date(", "").replace(")/", ""); 
Long timeInMillis = Long.valueOf(datereip); 
calendar.setTimeInMillis(timeInMillis); 
System.out.println(calendar.getTime().toString("dd-MMM-yyyy h:mm tt"));//It Will Be in format 29-OCT-2014 2:26 PM 
2

首先替换字符串像这样:

String str= ConvertMilliSecondsToFormattedDate(strDate.replace("/Date(","").replace(")/", ""));

然后将其转换是这样的:

public static String ConvertMilliSecondsToFormattedDate(String milliSeconds){ 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(Long.parseLong(milliSeconds)); 
    return simpleDateFormat.format(calendar.getTime()); 
}