Skip to content Skip to sidebar Skip to footer

Convert Datetime Object Java To Json String

I want to convert date time object in java to json string in format as below: {'date':'/Date(18000000+0000)/'} I did like this but it didn't give me the format i desired: JSONObje

Solution 1:

Here is my solution, although it is not a good way, but I finally find a workable solution.

SimpleDateFormat format = newSimpleDateFormat("Z");
Date date = newDate();
JSONObjectobject = newJSONObject();
object.put("date", "/Date(" + String.valueOf(date.getTime()) + format.format(date) + ")/");

Solution 2:

publicstaticStringconvertToJsonDateTime(String javaDate)

  {
     SimpleDateFormat dateFormat = newSimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        Date currentDate = null;
        try {
            currentDate = dateFormat.parse(javaDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long time =currentDate.getTime();
    return"\\/Date("+time+"+0000)\\/";
}

Solution 3:

My solution : I think this is the simplest Way

DateFormat dateFormat=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
yourJsonObject.accumulate("yourDateVarible",dateFormat.format(newDate()));

Solution 4:

The date format that you want is /Date(<epoch time><Time Zone>)/. You can get the epoch time in java using long epoch = System.currentTimeMillis()/1000;(found at this link) and the time zone you can get by using the date and time patteren as Z. Then combine all the strings into one and store it to the Json Object. Other possibility is that the time you are getting from iOS device may be of the pattern yyMMddHHmmssZ as got from here. Check the output on the iOS device at different times and identify the correct pattern.

Solution 5:

From json.org's description of JSONObject:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

This library doesn't support the "complex" mapping of a Date to a JSON representation. You'll have to do it yourself. You may find something like SimpleDateFormat helpful.

Post a Comment for "Convert Datetime Object Java To Json String"