使用jQuery / JS来确定星期几

时间:2009-07-23 20:33:14

标签: javascript jquery date

是否有使用JavaScript或jQuery的方法来确定它是星期几?例如,如果用户在框中选择的日期是星期日,我可以提醒他们。

6 个答案:

答案 0 :(得分:56)

new Date().getDay();  //0=Sun, 1=Mon, ..., 6=Sat

另请参阅:MDN上的Javascript Date Object

谨慎提示:这会在浏览器上返回星期几。由于地球不平坦,某些用户的星期几可能与您服务器的星期几不同。这可能与您的项目有关,也可能与之无关......

如果您正在进行大量日期工作,可能需要查看JavaScript日期库,例如DatejsMoment.js

答案 1 :(得分:21)

如果您只需要在页面中使用一次,请保持简单......

["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][(new Date()).getDay()]

我认为扩展并不是一件大事,但因为我在评论中有3张国际化票数......

// dictionary version
({
  es: ["Domingo", "Lunes",  "Martes",  "Miércoles", "Jueves",   "Viernes", "Sábado"],
  en: ["Sunday",  "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",  "Saturday"]
})['en'][(new Date()).getDay()]
// returns Wednesday

// list version
langs=['en','es']

[
  ["Domingo", "Lunes",  "Martes",  "Miércoles", "Jueves",   "Viernes", "Sábado"],
  ["Sunday",  "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",  "Saturday"]
][langs.indexOf('es')][(new Date()).getDay()]
// returns Miércoles

最后,代码高尔夫版......

["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur"][(new Date()).getDay()]+"day"

答案 2 :(得分:9)

today = new Date()
dayIndex = today.getDay()

...将为您提供“今天”的数字表示。

0 = Sunday
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday

答案 3 :(得分:6)

更清晰,更详细的答案:

var days = [
    'SUN', //Sunday starts at 0
    'MON',
    'TUE',
    'WED',
    'THU',
    'FRI',
    'SAT'
];

d = new Date(); //This returns Wed Apr 02 2014 17:28:55 GMT+0800 (Malay Peninsula Standard Time)
x = d.getDay(); //This returns a number, starting with 0 for Sunday

alert (days[x]);

工作fiddle

答案 4 :(得分:2)

如果您需要大量日期处理,请查看DateJS

答案 5 :(得分:0)

发送日期,您将获得该月当天的位置。即15/02/2018是第三个星期四。

 /*return day postion and dayname */
    function weekAndDay(date) {
        var arrayWeek =[];
        var date = new Date(date),
        days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        prefixes = ['','First', 'Second', 'Third', 'Fourth', 'Fifth'];
        if (date.getDate() % 7 == 0) {
            var prefixes2 = date.getDate() / 7;
        }else{
            var prefixes2 = Math.ceil(date.getDate() / 7);
        }
        arrayWeek.push({
            'dayPos' : prefixes[prefixes2] ,
            'dayName' : days[date.getDay()]
        });
        return arrayWeek;
    }