Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...