3

I have: CreatedTime TIMESTAMP, UpdatedTime TIMESTAMP, Status Varchar, AutoID columns

in mysql. Through my service i got the following json format.

 {
        "CreatedTime": "\/Date(1457646424000)\/",
        "UpdatedTime": "\/Date(1457647761000)\/",
        "Status": "Open",
        "AutoID": 1
 }

I'm trying to convert the CreatedTime and UpdatedTime like below:

public String ConvertJsonDateTime(String jsondate)
{
    if (jsondate != "" && !jsondate.equals("") && jsondate != null && jsondate != "null") {
        jsondate = jsondate.replace("/Date(", "").replace(")/", "");
        long time = Long.parseLong(jsondate);
        Date d = new Date(time);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d).toString();
    } else {
        return "";
    }
}

But it returns the wrong details. for example in Table the CreatedTime is 2016-03-10 14:47:04 but the function ConvertJsonDateTime returns as 2016-03-11 03:17:04. How can i fix this one?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Vengat
  • 235
  • 1
  • 5
  • 16
  • 1
    Probably you have to set the correct `TimeZone` for your `SimpleDateFormat` – Erich Kitzmueller Mar 10 '16 at 13:58
  • 3
    `jsondate!=""` -> never comapre strings in Java using `==` or `!=`: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java And place `jsondate!=null` left-most in your expression: if it is null, `!jsondate.equals("")` will throw a NPE – Bart Kiers Mar 10 '16 at 13:59

1 Answers1

0

you need to set the correct timezone

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // GMT or any timezone

also, as Bart says, you NEVER compare strings using == or !=, ALWAYS use equals()

Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58