从数据和时间上领先0 [英] Leading 0 missing from data and time

查看:115
本文介绍了从数据和时间上领先0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能很好的转换日期从json格式返回的webservice。 Web服务以下列格式提供日期:

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:

数据示例:日期在json数据中看起来像这样。

Data example: The dates look like this in the json data

\/Date(1373875200000)\/

当前功能:这是我现在的功能

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;

}

用法:我使用以上功能

success: function(data) {

    if (data.d[0]) {
        $.each(data.d, function(index, data) {

            $("body").append(HumanDate(data.from) + '<br />');

        });
    } else {

当前输出:这是输出我现在得到,注意到缺少的0的

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

预期输出这是我想要的输出,注意额外的0的

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

问题:

我得到日期和时间格式化为预期的输出示例?

How do I get the date and time formatted as the Expected output examples?

推荐答案

我建议使用一个图书馆这种东西 - 像 Moment.js 这样的工作就能完美地完成这个工作(并给你一个负载,更多的功能,如加法/减法讨价还价)。

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).

使用moment.js,您的代码可能看起来像这样:

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

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

使用示例:

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

希望有所帮助。

这篇关于从数据和时间上领先0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆