0

あなたの助けが必要です、

サーバーから返される長い日付で動作する最初の 2 つの日付形式があります。ただし、関数 dateToMDY(date) を 3 番目の div に呼び出すと、日付形式は dd/mm/yyyy のままです。なんてつらい。ここで何が間違っていますか?すべてが順調に見えます。何か見逃しましたか?

<!DOCTYPE html>

<html>

<head>

<style type="text/css">

</style>

<script type="text/javascript">
function test() {

var x = "Mon Mar 5 00:00:00 EST 2012"

var y = "05/03/2012"

document.getElementById('divy1').innerHTML = dateToDMY(new Date(x))

document.getElementById('divy2').innerHTML = dateToMDY(new Date(x))

document.getElementById('divy3').innerHTML = dateToMDY(new Date(y))

}
function dateToDMY(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return ''+  (d <= 9 ? '0' + d : d)  +'/'+ (m<=9 ? '0' + m : m) + '/' + y;
}

function dateToMDY(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return ''+ (m<=9 ? '0' + m : m)+'/'+ (d <= 9 ? '0' + d : d)  + '/' + y;
}

</script>

</head>

<body onload="test()">

dd/mm/yyyy (DatePicker)
<div id="divy1"></div>
<br>
mm/dd/yyyy (SQL)
<div id="divy2"></div>
<br>
Default Date String should be converted to mm/dd/yyyy
<div id="divy3"></div>

</body>

</html>
4

3 に答える 3

0
Date.prototype.formatDate = function (format) {
    var date = this,
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear(),
        hours = date.getHours(),
        minutes = date.getMinutes(),
        seconds = date.getSeconds();

    if (!format) {
        format = "MM/dd/yyyy";
    }

    format = format.replace("MM", month.toString().replace(/^(\d)$/, '0$1'));

    if (format.indexOf("yyyy") > -1) {
        format = format.replace("yyyy", year.toString());
    } else if (format.indexOf("yy") > -1) {
        format = format.replace("yy", year.toString().substr(2, 2));
    }

    format = format.replace("dd", day.toString().replace(/^(\d)$/, '0$1'));

    if (format.indexOf("t") > -1) {
        if (hours > 11) {
            format = format.replace("t", "pm");
        } else {
            format = format.replace("t", "am");
        }
    }

    if (format.indexOf("HH") > -1) {
        format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf("hh") > -1) {
        if (hours > 12) {
            hours -= 12;
        }

        if (hours === 0) {
            hours = 12;
        }
        format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf("mm") > -1) {
        format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf("ss") > -1) {
        format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1'));
    }

    return format;
};

var d1 = new Date(1351596249000);
console.log(d1.formatDate("dd/MM/yy hh:mm"));

var d2 = new Date();
console.log(d2.formatDate("dd/MM/yy HH:mm t"));
于 2013-11-14T02:14:15.947 に答える