简体   繁体   English

在android中解析json日期字符串

[英]Parse json date string in android

I get a json string with number of milliseconds after 1970 from the server in my android app. 我在Android应用程序中从服务器获得了1970年以后的毫秒数的json字符串。

Looks like this: \\/Date(1358157378910+0100)\\/ . 看起来像这样: \\/Date(1358157378910+0100)\\/

How can I parse this into a Java calendar object, or just get some date value from it? 我如何将其解析为Java日历对象,或者只是从中获取一些日期值? Should I start with regex and just get the millisecons? 我应该从正则表达式开始,只是得到毫秒? The server is .NET. 服务器是.NET。

Thanks 谢谢

The time seems to also have the timezone there so I would do something like this: 时间似乎也有时区,所以我会做这样的事情:

String timeString = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
String[] timeSegments = timeString.split("\\+");
// May have to handle negative timezones
int timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
int millis = Integer.valueOf(timeSegments[0]);
Date time = new Date(millis + timeZoneOffSet);

Copied from the accepted answer, fixed some bugs :) 从接受的答案复制,修复了一些错误:)

    String json = "Date(1358157378910+0100)";
    String timeString = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
    String[] timeSegments = timeString.split("\\+");
    // May have to handle negative timezones
    int timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
    long millis = Long.valueOf(timeSegments[0]);
    Date time = new Date(millis + timeZoneOffSet);
    System.out.println(time);

是啊,ü可以substring你的json从“(”到“)”,转换成string来米利斯,并通过在calendar对象。

String millisString = json.substring(json.indexOf('('), json.indexOf(')'));

I think you can get like this: 我想你可以这样:

json.getAsJsonPrimitive().getAsString();

json it's a JsonElement json它是一个JsonElement

EDIT: You can send without the Date(), just the numbers, can't you? 编辑:你可以发送没有日期(),只是数字,不是吗? And if you are using JSON, why don't work with the Date Object? 如果您使用的是JSON,为什么不使用Date对象?

Try this.. 试试这个..

String jsonDate = "\/Date(1358157378910+0100)\/";
String date = "";
 try {
String results = jsonDate.replaceAll("^/Date\\(","");
results = results.substring(0, results.indexOf('+'));                       
long time = Long.parseLong(results);
Date myDate = new Date(time);

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
date = sdf.format(myDate);
    System.out.println("Result Date: "+date);
} 
catch (Exception ex) {
     ex.printStackTrace();
     }

Here is a more complete solution, based on @pablisco answer: 这是一个更完整的解决方案,基于@pablisco答案:

public class DateUtils {

    public static Date parseString(String date) {

        String value = date.replaceFirst("\\D+([^\\)]+).+", "$1");

        //Timezone could be either positive or negative
        String[] timeComponents = value.split("[\\-\\+]");
        long time = Long.parseLong(timeComponents[0]);
        int timeZoneOffset = Integer.valueOf(timeComponents[1]) * 36000; // (("0100" / 100) * 3600 * 1000)

        //If Timezone is negative
        if(value.indexOf("-") > 0){
            timeZoneOffset *= -1;
        } 

        //Remember that time could be either positive or negative (ie: date before 1/1/1970) 
        time += timeZoneOffset;

        return new Date(time);
    }
}

Some of the other Answers such as by pablisco are correct about parsing the string to extract the number, a count of milliseconds since epoch. 一些其他答案,例如pablisco ,对于解析字符串以提取数字是正确的,这是自纪元以来的毫秒数。 But they use outmoded date-time classes. 但他们使用过时的日期时间类。

java.time java.time

Java 8 and later has the java.time framework built-in. Java 8及更高版本内置了java.time框架。 A vast improvement. 一个巨大的进步。 Inspired by Joda-Time . 灵感来自Joda-Time Defined by JSR 310 . JSR 310定义。 Extended by the ThreeTen-Extra project. ThreeTen-Extra项目扩展。 Back-ported to Java 6 & 7 by the ThreeTen-BackPort project, which is wrapped for Android by the ThreeTenABP project. 通过ThreeTen-BackPort项目反向移植到Java 6和7,该项目由ThreeTenABP项目包装为Android。

Consider the two parts of your input separately. 分别考虑输入的两个部分。 One is a count from epoch in milliseconds, the other an offset-from-UTC . 一个是来自epoch的计数,以毫秒为单位,另一个是来自UTC偏移量

Assuming the source used the same epoch as java.time (the first moment of 1970 in UTC), we can use that to instantiate an Instant object. 假设源使用与java.time相同的纪元(1970年的第一个UTC时刻),我们可以使用它来实例化一个Instant对象。 An Instant is a moment on the timeline in UTC . InstantUTC时间轴上的一个时刻。

    String inputMillisText = "1358157378910";
    long inputMillis = Long.parseLong ( inputMillisText );
    Instant instant = Instant.ofEpochMilli ( inputMillis );

Next we parse the offset-from-UTC. 接下来我们解析来自UTC的偏移量。 The trick here is that we do not know the intention of the source. 这里的诀窍是我们不知道来源的意图。 Perhaps they meant the intended date-time is an hour behind UTC and so we should follow that offset text as a formula, adding an hour to get to UTC. 也许他们的意思是预期的日期时间 UTC 一个小时,因此我们应该将该偏移文本作为一个公式,增加一个小时来达到UTC。 Or they meant the displayed time is one hour ahead of UTC. 或者他们意味着显示的时间 UTC 一个小时。 The commonly used ISO 8601 standard defines the latter, so we will use that. 常用的ISO 8601标准定义了后者,因此我们将使用它。 But you really should investigate the intention of your data source. 但你真的应该调查你的数据源的意图。

    String inputOffsetText = "+0100";
    ZoneOffset zoneOffset = ZoneOffset.of ( inputOffsetText );

We combine the Instant and the ZoneOffset to get an OffsetDateTime . 我们将InstantZoneOffset结合起来以获得OffsetDateTime

    OffsetDateTime odt = OffsetDateTime.ofInstant ( instant , zoneOffset );

Dump to console. 转储到控制台。

    System.out.println ( "inputMillis: " + inputMillis + " | instant: " + instant + " | zoneOffset: " + zoneOffset + " | odt: " + odt );

inputMillis: 1358157378910 | inputMillis:1358157378910 | instant: 2013-01-14T09:56:18.910Z | 时间:2013-01-14T09:56:18.910Z | zoneOffset: +01:00 | zoneOffset:+01:00 | odt: 2013-01-14T10:56:18.910+01:00 odt:2013-01-14T10:56:18.910 + 01:00

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

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