Brian
Brian

Reputation: 412

How to convert a JSON lib formatted JSON date to a Javascript Date

Sourceforges JSON-lib (http://json-lib.sourceforge.net) produces a JSON date format like this:

{
    "date":10,
    "day":5,
    "hours":0,
    "minutes":0,
    "month":5,
    "nanos":0,
    "seconds":0,
    "time":1307660400000,
    "timezoneOffset":-60,
    "year":111 //this is 2011
}

Is there an easy way to convert this into a Javascript date object or should I just go through and set all the variables on the date object manually?

I've searched all over to find this with no luck! (apologies if the answer is lying around somewhere, I just can't seem to find it)

Upvotes: 2

Views: 848

Answers (2)

monjer
monjer

Reputation: 2929

It seems that in the json-lib project home page , there are no example explain the the process of Date.But as soon as you search json-lib's API,you will finally get the answer.

Here you can use this method below to process java.util.Date class. You can define your own format pattern and use the JsonConfig to register a custom JsonValueProcessor that used to process the Date class.

public static final JSON serializerObjWithFormatDate(Object javaObj){
    
    String pattern = "yyyy-MM-dd HH:mm:ss";
    
    final SimpleDateFormat fm =  new SimpleDateFormat(pattern);
    
    JsonConfig jsonCfg = new JsonConfig();
    
    jsonCfg.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
        
        @Override
        public Object processObjectValue(String key, Object value, JsonConfig cfg) {
            if (value == null) {  
                  return "";  
            } else {  
                  return fm.format((Date)value);
            }
           
        }
        
        @Override
        public Object processArrayValue(Object date, JsonConfig arg1) {
             return fm.format((Date)date);  
        }
    });
    
    return JSONSerializer.toJSON(javaObj ,jsonCfg);
}

The param javaObj is the java object who has Date class instances.

May it be helpful .

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

It looks like time is the epoch in msec, so you can just do: new Date(object['time'])

You will need to of course parse this into an object first.

Upvotes: 1

Related Questions