[英]Cannot get days of the month that end in 31 in Javascript
I am putting an easter egg into my program that causes a jack-o-lantern image to appear on Halloween, but I cannot get the code to recognize October 31st as a month/day. 我在程序中放了一个复活节彩蛋,该彩蛋使万圣节那天出现了南瓜灯,但我无法获得将10月31日识别为月/日的代码。 When I do a console.log on my code, it feeds back "Mon Oct 30 2017" instead of the 31st.
当我在代码上执行console.log时,它会反馈“ 2017年10月30日星期一”,而不是31日。
var today = new Date();
var halloween = new Date(today.getFullYear() + '10-31');
console.log(halloween.toDateString());
console.log(today.toDateString());
if (today.toDateString() === halloween.toDateString()) {
printedMsg.innerHTML = rewardMsg + 'You deserve a spooky treat! ' +
'<img src="https://preview.c9users.io/mkrul/color_project/reward-imgs/boo.jpg">';
}
EDIT: I put the missing hyphen in front of '-10-31', but the console is still showing me "Mon Oct 30 2017" 编辑:我把丢失的连字符放在'-10-31'前面,但控制台仍向我显示“ Mon Oct 30 2017”
var halloween = new Date(today.getFullYear() + '-10-31');
You are missing a hyphen: 您缺少连字符:
var today = new Date();
var halloween = new Date(today.getFullYear() + '-10-31');
console.log(halloween.toDateString());
Will return 将返回
Tue Oct 31 2017
In ECMAScript, parsing strings is problematic, and even if you get the format right, you're passing a date format that will be treated as UTC so represent the day before the day you want for users west of Greenwich. 在ECMAScript中,解析字符串是有问题的,即使您使用正确的格式,也要传递一种将被视为UTC的日期格式,因此代表格林威治西部用户想要的日期的前一天。
Also see Why does Date.parse give incorrect results? 另请参见为什么Date.parse给出不正确的结果?
So don't rely on the built-in parser, pass the components directly: 因此,不要依赖内置的解析器,直接传递组件:
var halloween = new Date(new Date().getFullYear(), 9, 31); console.log('Halloween is on ' + halloween.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.