Article 5K336 CodeSOD: A Date With Yourself

CodeSOD: A Date With Yourself

by
Remy Porter
from The Daily WTF on (#5K336)

Once upon a time, someone wanted to add a banner to a web page. They also wanted the banner to only appear after a certain date. Jack stumbled across their implementation when trying to understand why the banner would vanish for two weeks at the start of every month.

// get datevar MyDate = new Date();var MyDateString;MyDate.setDate(MyDate.getDate());MyDateString = ('0' + MyDate.getDate()).slice(-2) + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2) + '-' + MyDate.getFullYear();if (MyDateString > '13-04-2014') { // do stuff...}

So, let's just start with the bad date handling, complete with hacked together string padding. We convert the actual date to a date string, and then compare against the date string instead of the actual date itself. Yes, very bad, very useless, and clearly the source of the bug that got Jack's attention. Since it's string comparisons, '01-05-2021' is "before" '13-04-2014'.

But I had to skip over something important to get there.

MyDate.setDate(MyDate.getDate());

I love that line. It's useless. It has nothing actually to do with what the code is actually trying to do. It's the sort of thing that even a developer who doesn't understand anything would have to read that and wonder why it was there.

But it's there. It isn't going anywhere.

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today! TheDailyWtf?d=yIl2AUoC8zA4Lpb92bHavo
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments