我对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()
索引到正确的值
发布于 2011-01-28 06:50:20
是的,你需要数组。
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];
或者,您可以使用date.js库。
编辑:
如果你打算经常使用它们,你可能想要扩展Date.prototype
的可访问性。
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
发布于 2018-05-11 21:17:31
使用标准的javascript Date类。不需要数组。不需要额外的库。
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);
console.log(prnDt);
发布于 2016-02-19 19:51:05
您还可以通过以下方式扩展date对象以返回Weekday:
Date.prototype.getWeekDay = function() {
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
return weekday[this.getDay()];
}
因此,您只能调用date.getWeekDay();
https://stackoverflow.com/questions/4822852
复制相似问题