0

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. When I do a console.log on my code, it feeds back "Mon Oct 30 2017" instead of the 31st.

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"

var halloween = new Date(today.getFullYear() + '-10-31');
Misha Krul
  • 321
  • 3
  • 13
  • https://stackoverflow.com/questions/17959660/todatestring-decrements-my-date – JJJ Sep 04 '17 at 14:06
  • Probably a duplicate of [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Sep 04 '17 at 22:58

2 Answers2

0

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
Stuart
  • 6,630
  • 2
  • 24
  • 40
  • I put the hyphen in, and it's still returning "Mon Oct 30 2017" in the console. – Misha Krul Sep 04 '17 at 14:01
  • 1
    What? If I literally copy and paste the above code into my console, I get `Tue Oct 31 2017`. – Stuart Sep 04 '17 at 14:04
  • You are in a different time zone. `.toDateString()` outputs the local time – one of you lives east of Greenwich, the other west of Greenwich. – JJJ Sep 04 '17 at 14:07
  • I also copy/pasted it. I swear it's still showing me the 30th. – Misha Krul Sep 04 '17 at 14:08
  • I suppose I should convert it to UTC then? – Misha Krul Sep 04 '17 at 14:09
  • No, then you'd show the picture when it's Halloween in western Europe, not where the user is from. Just do `if( today.getDate() === 31 && today.getMonth() === 9 ) ...` – JJJ Sep 04 '17 at 14:11
  • The issue is that ISO 8601 format date strings are treated as UTC. So don't use the parser, pass the values directly. It's somewhat illogical to have the values, convert them to a string, then give them to a parser to convert to a Date when you can bypass the parser and its issues altogether. – RobG Sep 04 '17 at 22:59
0

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.

Also see Why does Date.parse give incorrect results?

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());
RobG
  • 142,382
  • 31
  • 172
  • 209