Thursday, February 21, 2019

Avoid inconsistent Date object definitions

I recently took a pop-quiz question on this, and failed. Errrrr...

Pop Quiz

What is the Date value of the following code?

new Date(2016, 5, 31);

My Answer:

May 31, 2016

Makes sense, right? At least to 70% of us developers who are not JS experts?

See more fun questions at https://app.enkipro.com.

Correct Answer:

June 1, 2016

Since JavaScript early days leveraged a lot techniques and patterns from Java, I looked up both definitions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#Date-int-int-int-
https://www.w3schools.com/js/js_dates.asp

My Further Thoughts

With all the new technologies and programming languages (along with updates to these languages), I'm actually shocked that we haven't provide better consistency with a common class instantiation like the Date object. Particularly, in JavaScrpt.

Since the Time parameters all start from 0, this makes sense and is consistent. However, for the Date parameters, since 'day' starts with 1 and makes the most sense, then why not start the month and the year with '1' as well? Nope, instead, the creators decided to make the month slightly difficult (and very difficult when we add in how fast developers need to work nowadays) by starting the value at '0'. But, no one in the world uses '0' to represent a month, and if it's an array index then define the parameter as such for ALL parameters in the Date definition. If you're not already confused, then try the year with a starting value of '1' and see this is actually 1901. Why, just because the creators somehow thought that programming would only be useful for years 1900-1999 (or shortcut values as 0-99). Thanks guys. Especially to Java guys who decided to just deprecate this and recommend using more code for date formatting (i.e. SimpleDateFormat).
*By the way, I wouldn't complain if these two programming languages weren't so currently popular and in demand.

My Solution

To avoid this unnecessarily confusing definition and prevent making mistakes within my apps, I would create a Date wrapper object that would allow for easier reading of my code. And consistency. That's [programming language] agnostic.

No comments:

Post a Comment