将Date参数传递给函数

时间:2011-08-24 09:56:51

标签: javascript

如何将Date的参数传递给另一个函数?我的代码:

var myDate = new Date(data.GetOPCResult.DateTime.match(/\d+/)[0] * 1);
var datlabel = document.getElementById("ct");
datlabel.innerHTML = GetTime(myDate);

和GetTime功能代码:

function GetTime(DateTime) {
    var month = (DateTime.getMonth() < 10) ? "0" + (DateTime.getMonth() + 1) : (DateTime.getMonth() + 1);
    var day = (DateTime.getDate() < 10) ? "0" + DateTime.getMonth() : DateTime.getMonth();
    var hour = (DateTime.getHours() < 10) ? "0" + DateTime.getHours() : DateTime.getHours();
    var minute = (DateTime.getMinutes() < 10) ? "0" + DateTime.getMinutes() : DateTime.getMinutes();
    var second = (DateTime.getSeconds() < 10) ? "0" + DateTime.getSeconds() : DateTime.getSeconds();
    return DateTime.getDate() + "." + month + "." + DateTime.getFullYear() + " " + hour + ":" + minute + ":" + second;
}

2 个答案:

答案 0 :(得分:3)

这对我有用

function GetTime(d) {
    var month = (d.getMonth() < 10) ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1);
    var day = (d.getDate() < 10) ? "0" + d.getMonth() : d.getMonth();
    var hour = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
    var minute = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
    var second = (d.getSeconds() < 10) ? "0" + d.getSeconds() : d.getSeconds();

    return d.getDate() + "." + month + "." + d.getFullYear() + " " + hour + ":" + minute + ":" + second;
}

alert(GetTime(new Date()));

您确定要传递有效的Date对象吗?尝试将new Date()而不是myDate传递给GetTime。如果可行,则myDate变量不是有效的Date对象。

答案 1 :(得分:0)

你的代码很好。尽管如此,一点点的重新分解也会有所帮助。

function GetTime(date) {
    var day = zeroPad(date.getDate(), 2);
    var month = zeroPad(date.getMonth() + 1, 2);
    var year = zeroPad(date.getFullYear(), 4);
    var hour = zeroPad(date.getHours(), 2);
    var minute = zeroPad(date.getMinutes(), 2);
    var second = zeroPad(date.getSeconds(), 2);
    return day + "." + month + "." + 
        year + " " + hour + ":" + 
        minute + ":" + second;
}

function zeroPad(num, count) {
    var z = num + '';
    while (z.length < count) {
        z = "0" + z;
    }
    return z;
}

另外请检查data.GetOPCResult.DateTime是什么。我会说会这样做。

var myDate = new Date( (data.GetOPCResult.DateTime || "")
                .replace(/-/g,"/")
                .replace(/[TZ]/g," ") );