最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Problems with Date() in JavaScript - it adds one month? - Stack Overflow

programmeradmin1浏览0评论

I have a strange problem with Date() in JavaScript.

I have the following simple code:

var date = new Date(2013, 11, 01, 00, 00, 0, 0);
alert(date);

That should set the Date to 01 November 2013 00:00:00:00 But instead it sets it to December? As you can see in this fiddle /

What is wrong?

I have a strange problem with Date() in JavaScript.

I have the following simple code:

var date = new Date(2013, 11, 01, 00, 00, 0, 0);
alert(date);

That should set the Date to 01 November 2013 00:00:00:00 But instead it sets it to December? As you can see in this fiddle http://jsfiddle.net/CBqK2/

What is wrong?

Share Improve this question edited Oct 14, 2013 at 11:05 Grevling 4664 silver badges19 bronze badges asked Oct 14, 2013 at 10:57 mschadeggmschadegg 7999 silver badges21 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 18

JavaScript months are 0 based, just to confuse you.

From MDN for the Date constructor:

month Integer value representing the month, beginning with 0 for January to 11 for December.

So for your example:

var date = new Date(2013, 10, 01, 0, 0, 0, 0);
alert(date);

You can read more about Date on MDN here.

Set the second value to 10. Date class begins with a 0 for January like in an Array ;)

The Date() returns the month (from 0 to 11) for the specified date, according to local time.

eg:January is 0, February is 1, and so on.

if you want to start from 0 onwards use below format

var date = new Date('2013/10/01');

the Date has the list of months weekdays starting from zero.

for months it is 0-11 for Jan to Dec and for Week days it is 0-6 for Sun - Sat.

when you say.

var date = new Date('1381751517000') // I have used the timestamp in milliseconds for 2013-10-14T11:51:00 as js accepts timestamp in milliseconds.

now if we say

day = date.getDay();

it return 1, i.e Monday,

month = date.getMonth()

it returns 9 i.e October.

in the same way when we create the date using the format ('YYYY,MM,DD,HH,mm,ss,ms') we should give the input also in the same way.

发布评论

评论列表(0)

  1. 暂无评论