开发者

Why is this returning -1 in JavaScript

d.getTime().toString().search(/Wed/i)

I don't get it... typeof returns string, and if i copy and paste "Wed Jul 14 2010 15:35:53 GMT-0700 (PST)" and save it to the var str and do str.search(/Wed/i) it returns 0 but when i do it like above i always get -1, even tho, as i said, it returns a string typeof.

Any ideas how to check if Wed is in that str?

Just for reference, i'm looping through 7 days, checking for Wed, if it's wed, i save the current date and break ou开发者_运维技巧t of the loop. If you know a better way let me know. Right now im just doing a while(x<=6)


getTime on a Date returns the number of milliseconds since 1 January 1970, so won't contain the string 'Wed'.

Perhaps you meant d.toString().search(/Wed/i) instead?

If d is an instance of Date, then a better way to check if it is a Wednesday would be to test if the result of getDay is 3:

d.getDay() == 3


The reason it returns -1 is that "Wed" will never appear in your string, because "getTime()" returns a big number: the number of milliseconds since the epoch.

Calling "toString()" on that big number still returns a big number, with the digits formatted as a string, as in "1278975122089". It does NOT return the date and time, as in "Mon Jul 12 15:49:59 PDT 2010".

The getTime() method returns the number of milliseconds since midnight of January 1, 1970 and the specified date.

Try using the following instead, without the getTime() call:

d.toString().search(/Wed/i)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜