[javascript] 如何获得星期几和一年的月份?



Answers

正如@ L-Ray已经建议的那样,您也可以查看moment.js

样品

var today = moment();
var result = {
  day: today.format("dddd"),
  month: today.format("MMM")
}

document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Question

我对JavaScript不太了解,而我发现的其他问题与日期操作有关,不仅仅是根据需要获取信息。

目的

我希望得到如下格式的日期:

2011年1月27日星期四17:42:21印刷

到目前为止,我得到了以下内容:

var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();

h = checkTime(h);
m = checkTime(m);
s = checkTime(s);

var prnDt = "Printed on Thursday, " + now.getDate() + " January " + now.getFullYear() + " at " + h + ":" + m + ":" s;

我现在需要知道如何获得星期几和一年中的月份(他们的名字)。

有没有一种简单的方法来实现它,或者我应该考虑使用数组,我会简单地使用now.getMonth()now.getDay()索引到正确的值?







var GetWeekDays = function (format) {
    var weekDays = {};

    var curDate = new Date();
    for (var i = 0; i < 7; ++i) {
        weekDays[curDate.getDay()] = curDate.toLocaleDateString('ru-RU', {
            weekday: format ? format : 'short'
        });

        curDate.setDate(curDate.getDate() + 1);
    }

    return weekDays;
};

me.GetMonthNames = function (format) {
    var monthNames = {};

    var curDate = new Date();
    for (var i = 0; i < 12; ++i) {
        monthNames[curDate.getMonth()] = curDate.toLocaleDateString('ru-RU', {
            month: format ? format : 'long'
        });

        curDate.setMonth(curDate.getMonth() + 1);
    }

    return monthNames;
};



你还可以做的一件事是扩展日期对象返回平日:

Date.prototype.getWeekDay = function() {
    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    return weekday[this.getDay()];
}

所以,你只能调用date.getWeekDay();




Links