简体   繁体   English

如何将 Json 日期转换为 Java 日期

[英]How can I convert Json Date to Java Date

I am trying to convert Json date string to java date format.我正在尝试将 Json 日期字符串转换为 java 日期格式。 However, it gives error when it comes to "return df.parse( tarih )" line.但是,当涉及到“return df.parse( tarih )”行时,它会出错。

JSON : JSON :

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

Java code : 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 );

}

When I call this method, tarih parameter is: /Date(1323087840000+0200)/当我调用这个方法时,tarih 参数是:/Date(1323087840000+0200)/

As you're interested in a Date object and the JSON occurs to me to be a unix timestamp.由于您对Date对象感兴趣,而我认为 JSON 是一个 unix 时间戳。
Therefore I'd recommend you the Date(long milliseconds) constructor :)因此,我建议您使用Date(long milliseconds)构造函数:)

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

Where getTimeStampFromTarih extracts the milliseconds before the occurrence of "+"其中getTimeStampFromTarih提取“+”出现前的毫秒数

This will work surely这肯定会奏效

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

First replace string like this :首先像这样替换字符串:

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

Then Convert it like this:然后像这样转换它:

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

You will Need to type cast date:您将需要输入演员日期:

String rawdate = "/Date(1995769286000)/";
Calendar calendarins = Calendar.getInstance();
String datereip = rawdate.replace("/Date(", "").replace(")/", "");
Long timeInMillis = Long.valueOf(datereip);
calendar.setTimeInMillis(timeInMillis);
System.out.println(calendar.getTime().toString("dd-MMM-yyyy h:mm tt"));

Unless you have a reason not to, you should be using a parser to serialize and de-serialize objects.除非您有理由不这样做,否则您应该使用解析器来序列化和反序列化对象。 Like Jackson parser.就像杰克逊解析器。

java.time时间

This is the modern answer (since 2014).这是现代答案(自 2014 年以来)。

First I want to make sure the timestamp I have really lives up to the format I expect.首先,我想确保我拥有的时间戳确实符合我期望的格式。 I want to make sure if one day it doesn't, I don't just pretend and the user will get incorrect results without knowing they are incorrect.我想确保有一天它不会,我不只是假装,用户会在不知道它们不正确的情况下得到错误的结果。 So for parsing the timestamp string, since I didn't find a date-time format that would accept milliseconds since the epoch, I used a regular expression:因此,为了解析时间戳字符串,由于我没有找到接受自纪元以来的毫秒数的日期时间格式,因此我使用了正则表达式:

    String time = "/Date(1479974400000-0800)/";
    Pattern pat = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
    Matcher m = pat.matcher(time);
    if (m.matches()) {
        Instant i = Instant.ofEpochMilli(Long.parseLong(m.group(1)));
        System.out.println(i);
    }

This prints:这打印:

2016-11-24T08:00:00Z 2016-11-24T08:00:00Z

It is not clear to me whether you need to use the zone offset and for what purpose.我不清楚您是否需要使用区域偏移量以及用于什么目的。 But since we've got it, why not retrieve it from the matcher and use it for forming an OffsetDateTime , a date and time with UTC offset.但是既然我们已经得到了它,为什么不从匹配器中检索它并使用它来形成一个OffsetDateTime ,一个带有 UTC 偏移量的日期和时间。 Here's how:就是这样:

        ZoneOffset zo = ZoneOffset.of(m.group(2));
        OffsetDateTime odt = OffsetDateTime.ofInstant(i, zo);
        System.out.println(odt);

2011-12-05T14:24+02:00 2011-12-05T14:24+02:00

If you need an old-fashioned java.util.Date for some legacy API:如果你需要一个老式的java.util.Date来处理一些遗留 API:

        System.out.println(Date.from(i));

Or if using the backport mentioned in the links below:或者,如果使用以下链接中提到的向后移植:

        System.out.println(DateTimeUtils.toDate(i));

On my computer it prints在我的电脑上打印

Mon Dec 05 13:24:00 CET 2011 2011 年 12 月 5 日星期一 13:24:00 CET

The exact output will depend on your time zone.确切的输出将取决于您的时区。

Links链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM