如何获得星期几和一年中的月份? [英] How to get the day of week and the month of the year?

查看:36
本文介绍了如何获得星期几和一年中的月份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know much about Javascript, and the other questions I found are related to operations on dates, not only getting the information as I need it.

我希望获得以下格式的日期:

I wish to get the date as below-formatted:

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

Printed on Thursday, 27 January 2011 at 17:42:21

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

So far, I got the following:

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;

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

I now need to know how to get the day of week and the month of year (their names).

是否有一种简单的方法来实现它,或者我应该考虑使用数组,我只需使用 now.getMonth()now.getDay()<索引到正确的值/代码>?

Is there a simple way to make it, or shall I consider using arrays where I would simply index to the right value using now.getMonth() and now.getDay()?

推荐答案

是的,你需要数组.

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 库.

Or you can use the date.js library.

如果您要经常使用这些,您可能需要扩展 Date.prototype 以实现可访问性.

If you're going to use these frequently, you may want to extend Date.prototype for accessibility.

(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();

这篇关于如何获得星期几和一年中的月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆