Tuesday, 13 November 2012

Google Forms and JavaScript Dates

Updated: +Eric Koleda was kind enough to point out JavaScript's date parsing capabilities which are much more elegant than my previous workaround so this post has been edited to avoid leading anyone else astray!

Last time in our Snippets Bakery Project we looked at constructing HTML tables in confirmation emails. This time we're looking at working with dates - crucial when your products have a short shelf life!

One of the most common pieces of information you need to collect in a form is a date. Unfortunately, Google Forms doesn't include a flashy jQuery-like date picker and the most common approach seems to be providing a free text box and hoping that respondents fill in dates in a useful format. However, responses that vary from "Monday" to "Monday the nineteenth of November" to "19-11-2012" are less than ideal if you need to perform calculations based on a specified date.

3 x the fun fields
A work around I have used isn't terribly graceful in that it requires three fields to be filled in but it is relatively simple to code and does the job.

So, what do we want to achieve with this snippet?

  • A date string form that is easily interpreted by humans
  • A JavaScript date instance with which we are able to do arithmetic
  • To avoid any international ambiguity over day and month order

Transatlantic Translation

So how do we go about it? To achieve the third aim I want to build using (shortened) month names in to the specification. It could be argued that naming the field "Month" or the fact that there's only 12 numerical options rather than 31 could be enough but if you were in a hurry and wanted to select the second of January it is conceivable that you could select the first of February in error if you select 1-2. So: month names it is.

To create a human readable date string, all we really need to do is attach the values with a splitter character of your preference. In JavaScript you can easily join strings with the concatenation operator (+)

Handily, JavaScript will parse datestrings in some formats easily so having Months as names doesn't present us with a problem. This post was much simpler than I originally envisaged!

Further reading - 10 ways to format time and date using JavaScript - Working with dates


  1. Because of the lack of a date drop-down, I was cornered into writing a Web App. This means I can use jQuery, and all the other goodies like input suggestions or drag and drop etc. I think the end-user advantages of using HTML out-weigh the ease of use of the UI Builder.

  2. I think that is probably the best solution, assuming that you have the time and expertise to take that road. I'll have to cover that hear later...!