Leading 0 missing from data and time

datetime, javascript, jquery, json

Solution

I'd suggest using a library for this kind of thing -- something like Moment.js would do the job perfectly (and give you a load more functionality like date addition/subtraction into the bargain).

With moment.js, your code could look like this:

function HumanDate(date) {
    return moment(date).format('MM/DD/YYYY HH:mm');
}

usage example:

alert(HumanDate("\/Date(1373875200000)\/"));
//alerts "07/15/2013 09:00"

Hope that helps.

Problem

I have a function which works well, for converting dates from a webservice returned in json format. The webservices gives dates in the following type of format: Data example: The dates look like this in the json data ``` \/Date(1373875200000)\/ ``` Current function: This is the current function I have ``` function HumanDate(date) { var jsondateString = date.substr(6); var current = new Date(parseInt(jsondateString)); var month = current.getMonth() + 1; var day = current.getDate(); var year = current.getFullYear(); var hour = current.getHours(); var minute = current.getMinutes(); var datetime = day + "/" + month + "/" + year + " " + hour + ":" + minute return datetime; } ``` Usage: This is how I use the function above ``` success: function(data) { if (data.d[0]) { $.each(data.d, function(index, data) { $("body").append(HumanDate(data.from) + '<br />'); }); } else { ``` Current output: This is the output I currently get, notice the missing 0's ``` 2/7/2013 9:0 15/7/2013 9:30 15/10/2013 10:0 15/11/2013 10:30 ``` Expected output: This is the output I would like, notice the extra 0's ``` 02/07/2013 09:00 15/07/2013 09:30 15/10/2013 10:00 15/11/2013 10:30 ``` Question: How do I get the date and time formatted as the Expected output examples?

Original source

Related problems