Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading 0 missing from data and time

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?

like image 911
oshirowanen Avatar asked Sep 16 '25 04:09

oshirowanen


1 Answers

If you don't use a library, then you have to do some work, that is you have to put the "0" yourself.

Instead of simply concatenating day, you need to concatenate

(day<10 ? '0'+day : day)

and the same for the other fields.

But note that there are good javascript libraries filling this kind of gap. I personally used datejs for date manipulations.

like image 164
Denys Séguret Avatar answered Sep 18 '25 18:09

Denys Séguret