Parse json date string in android

2019-01-26 14:03发布

I get a json string with number of milliseconds after 1970 from the server in my android app.

Looks like this: \/Date(1358157378910+0100)\/.

How can I parse this into a Java calendar object, or just get some date value from it? Should I start with regex and just get the millisecons? The server is .NET.

Thanks

7条回答
beautiful°
2楼-- · 2019-01-26 14:43

I think you can get like this:

json.getAsJsonPrimitive().getAsString();

json it's a 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?

查看更多
Summer. ? 凉城
3楼-- · 2019-01-26 14:49

Yeah, u can substring your json from "(" to ")", convert string to millis and pass in calendar object.

String millisString = json.substring(json.indexOf('('), json.indexOf(')'));
查看更多
Animai°情兽
4楼-- · 2019-01-26 14:53

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. But they use outmoded date-time classes.

java.time

Java 8 and later has the java.time framework built-in. A vast improvement. Inspired by Joda-Time. Defined by JSR 310. Extended by the ThreeTen-Extra project. Back-ported to Java 6 & 7 by the ThreeTen-BackPort project, which is wrapped for Android by the ThreeTenABP project.

Consider the two parts of your input separately. One is a count from epoch in milliseconds, the other an offset-from-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. An Instant is a moment on the timeline in UTC.

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

Next we parse the offset-from-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. Or they meant the displayed time is one hour ahead of UTC. The commonly used ISO 8601 standard defines the latter, so we will use that. 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.

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

Dump to console.

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

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

查看更多
smile是对你的礼貌
5楼-- · 2019-01-26 14:54

Here is a more complete solution, based on @pablisco answer:

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);
    }
}
查看更多
【Aperson】
6楼-- · 2019-01-26 14:56

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();
     }
查看更多
走好不送
7楼-- · 2019-01-26 14:59

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);
查看更多
登录 后发表回答