开发者

How can i parse from SQL datetime to JSON and finally to java.util.Date?

i have a remote sql satabase, and i connect him by php with JSON.

I can get string and int data OK, but now i have a problem.... i have a datetime field on my SQL database, and i dont know how to get it with JSON into java.util.Date

this is the code i tryed, but it fails getting the Date correctly, it gives me an exception (java.lang开发者_如何转开发.ClassCastException: java.lang.String)

code:

JSONArray jArray = new JSONArray(result);


                for(int i=0;i<jArray.length();i++)
                {
                        JSONObject json_data = jArray.getJSONObject(i);                         
                        positions.add(new Position(json_data.getString("latitude"), json_data.getString("longitude"), (Date)json_data.get("timestamp")));
                 }


You will have to fetch the string sent in the JSON data and parse that string with something like SimpleDateFormat.


In my projects I have used two different solutions.

  1. Storing the Date not as Date but as long(milisecs since 1.1.1980). In Java you can get this with date.getTime(). There should also a methode in PHP. The get the Date Object in Java just pass the long value to the constructor(date= new Date(long_value)). With this Method you may have problems when dates comes from different time zones.

  2. Write the Date as a formatted Date String in the JSON. How you encode the Date is up to you. A short sample give below. see[1] for further infos.

To get the Date you need a SimpleDateFormater.

DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
try
{
  Date today = df.parse("2001.07.04 AD at 12:08:56 PDT");            
  System.out.println("Today = " + df.format(today));
}
catch (ParseException e)
{
  e.printStackTrace();
}

[1]http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜