AlexaDev Tuesday: Javascript Date Math

You may have seen skills that deliver a custom, daily response keyed to the day of the year. Today’s post demonstrates how to achieve this using Javascript date math.

 

Calendar WTF

 

Date vs. Day Of Year

First, it’s important to think in terms of day of year rather than calendar date. The number of days in a year can vary from 365-366, depending on whether or not it’s a Leap Year. If you don’t plan for that 366th day, in Leap Years your skill’s responses will be shifted ahead by one from February 29 through December 31, and in fact your skill will fail to deliver a response at all on that last, 366th day of the year.

Note that this approach will not work with “This Day in…” -type skills, because your responses will be keyed to day of the year (1-366), not calendar date (e.g., March 12, August 28, etc.). For a skill keyed to calendar date, you would have to create separate logic to handle Leap Years.

However, if all you’re trying to accomplish is delivery of a different, custom response each day, today’s post will show you how to do it in Javascript.

 

Array + Date Math = Thing of the Day Skill Response

In a nutshell, the code for a Thing of the Day type of skill needs to provide an array or table/database containing 366 entries plus logic to pull the correct array item for the current day.

In this example, let’s assume I’ve already declared an array called Words (array text content blanked out – your text goes between the quotation marks on each line):

Words Array

I understand that some developers prefer not to declare a Javscript array using new Array(), and of course you are free to use whichever method you prefer. This type of declaration is not essential to the date math.

So I’ve got a Words array with 366 unique text entries, one for each day of the year. Here’s an image of the code I used to pull the array entry for the current day-of-year (click here to view the code in a .txt file, for copy/paste use):

Date Math

 

Some Caveats

First, my method is just one among many to accomplish the same ends. There are many other approaches to be found on developer blogs, github, Stack Overflow and in various Javascript books and training courses. Here’s one example.

Second, the method shown does not take Daylight Savings Time into account because hour of the day (and therefore, DST) is not a factor in the specific skill where I used this code. If hour of the day or DST are potential problem areas for your skill, see this discussion on Stack Overflow for some alternative code samples.

 

Some of the most popular skills are Thing of the Day skills, so why not try your hand at building one of your own?