5

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 Answers 7

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Nice example, though i got an exception. It crashed when making "Integer.ValueOf" - it made an exception with invalid int. I think its because the value exceed the max value of an int. Making it to a long instead, make it work! :)
For dealing with negative timezone please take a look at my solution based on @pablisco answer
3

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);

2 Comments

Why didn't you simply fix the answer?
Ya, I've just done it. I didn't aware such kind of feature before. Thanks for letting me know. :)
1

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(')'));

Comments

1

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?

2 Comments

I haven't written the server side code. I just the app programmer.
Okay, you can get the whole string like a said, and them use the substring that @Veaceslav Gaidarji suggested, so you can test if the String wasn't null and if have the "(" and ")" characters.
0

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();
     }

Comments

0

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);
    }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.