简体   繁体   中英

How to convert normal date to JSON date in JavaScript?

My question is easy.

There is a lot of information about converting JSON date (Date/00213912321/) to normal date (7/03/14 10:00 am).

But I need to do the inverse. I have a normal date and I need it in JSON format. How can I achieve that?

I'm using jQuery so if there is some plugin that I can use, it'll be great.

If you have a regular date, perhaps the Date object can parse it.

var dateObj = new Date('7/03/14 10:00 am');
    timestamp = dateObj.getTime();  // timestamp is 1404396000000

There is no such thing as a JSON Date. JSON doesn't support any type for dates.

00213912321 appears to be epoch time. You can get that from a Date object with the getTime method.

Therefore:

var date = "Date/" + someDateObject.getTime()  + "/";
// convert json date into normal date.
function ConvertJsonDateString(jsonDate)
{
    var shortDate = null;

    if (jsonDate)
    {
        var regex = /-?\d+/;
        var matches = regex.exec(jsonDate);
        var dt = new Date(parseInt(matches[0]));
        var month = dt.getMonth() + 1;
        const monthNames = ["", "January", "February", "March", "April", "May", "June",
                                "July", "August", "September", "October", "November", "December"
                           ];
        var monthString =  monthNames[month];
        // var monthString = month > 9 ? month: '0' + month;
        var day = dt.getDate();
        var dayString = day > 9 ? day : '0' + day;
        var year = dt.getFullYear();
        shortDate = monthString + '-' + dayString + '-' + year;
    }
    return shortDate;
};

Ajax Json

{ "data": function (r) {
    var date = ConvertJsonDateString(r.Jsondate);
    var Expirydt = date == null ? "" :  date;
    return Expirydt;
    }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM