JavaScript,getDay()返回错误的数字 [英] Javascript, getDay() returning wrong number

查看:56
本文介绍了JavaScript,getDay()返回错误的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道javascript中的星期几从0开始,星期日= 0,星期六= 6.

To start off, I know that the day of week in javascript starts at 0, Sunday = 0, Saturday = 6.

但是,这里缺少一些简单的东西,但是下面的代码总是返回我想要的东西,但是少了1个.

However, there is something simple that I am missing here, but the following code always returns what I want, but 1 less.

这应该返回6,但返回5.

This should return 6, but returns 5.

var string = "2014-06-21";
var temp = new Date(string);
alert(temp.getDay());

任何人都知道发生了什么问题,以及如何解决?谢谢.

Anybody have any ideas whats going wrong, and how it may be fixed? Thanks.

推荐答案

如果您通过字符串创建日期,请务必指定时间:

If you create a date from a string be sure to specify the time:

var string = "2014-06-21 00:00:00";
var temp = new Date(string);
alert(temp.getDay());

您可能因为没有指定时间(在日期字符串中)而获得了前一天.在这种情况下,将使用您当前的时区(我的时间是GMT-03h)

You are probably getting the previous day because you are not specifying the time (in the date string). In this case, your current time zone will be used (mine is GMT-03h)

另一种选择是使用 Date 构造函数创建日期,该构造函数将数字作为参数:

Another option is to create a date using the Date constructor which takes numbers as it's parameters:

new Date(year,month,day);

或者,就您而言:

var temp = new Date(2014, 6, 21);
alert(temp.getDay());

这篇关于JavaScript,getDay()返回错误的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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