Javascript日期/时间格式

时间:2016-03-29 11:03:14

标签: javascript datetime date-format

我在网页上放了一个时钟,我需要格式化它,如下所示:

Wednesday 29 March 2016 12:01:11

这样秒就会改变。我这样做了如下所示:

var myVar = setInterval(function () { myFunction() }, 1000)

var dayName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
var monthName = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
function myFunction() {
    var d = new Date();

    var year = d.getFullYear();
    var month = d.getUTCMonth();
    var date = d.getUTCDate();
    var day = d.getUTCDay();

    var hours = d.getHours();
    if(hours < 10) {
        hours = "0" + hours;
    }
    var mins = d.getMinutes();
    var secs = d.getSeconds();
    if (secs < 10) {
        secs = "0" + secs;
    }

    var fullDateTime = dayName[day] + " " +  date + " " + monthName[month] + " " + year + " " + hours + ":" + mins + ":" + secs;

    document.getElementById("Time").innerHTML = fullDateTime;

}

我想知道是否有更好的方法来实现这一目标。

2 个答案:

答案 0 :(得分:0)

您可以使用toLocaleString而不是在数组中指定日期和月份。我修改了一下你的代码。

var myVar = setInterval(function () { myFunction() }, 1000)

function myFunction() {
    var d = new Date();
    var locale = "en-us";

    var year = d.getFullYear();
    var month = d.toLocaleString(locale, { month: "long" });
    var date = d.getUTCDate();
    var day = d.toLocaleString(locale, { weekday: "long" });

    var hours = d.getHours();
    if(hours < 10) hours = "0" + hours;

        var mins = d.getMinutes();
    if (mins < 10) mins = "0" + mins;

        var secs = d.getSeconds();
    if (secs < 10) secs = "0" + secs;

    var fullDateTime = day + " " +  date + " " + month + " " + year + " " + hours + ":" + mins + ":" + secs;

    document.getElementById("Time").innerHTML = fullDateTime;

}

jsfiddle中找到输出。

答案 1 :(得分:-1)

使用此库http://momentjs.com/

var myVar = setInterval(function () { myFunction() }, 1000)
function myFunction() {
    document.getElementById("Time").innerHTML = moment().format('dddd Do MMMM HH:mm:ss');
}