A Quick Handbook for Dates in JavaScript

Written by lenafaure | Published 2017/06/18
Tech Story Tags: programming | javascript | front-end-development | tech | coding

TLDRvia the TL;DR App

JavaScript has a built-in Date object that represents time. How can you use it and when will it be useful ?

Han Chau — unsplash.com

Suppose you are building an application that displays all the timetables of buses and trains in your area. The user can select a journey, and you want to be able to tell him how long his trip will take. To do so, you will have to take the arrival time and subtract it from the departure time.

Simply using the written expression of hours won’t be effective : how will you manage to calculate the journey of a night train leaving at 8pm and arriving at 7:58am the next morning? How will you handle the Orient-Express that leaves at 20h50 from Nice and arrives in Moscow nearly two days later ?

You have to have a unique representation of these two specific points in time, and this is where the Date Object comes in.

Ugur Akdemir — unsplash.com

The Date object in Javascript stores a unique representation of each date: an extremely large number, which holds the number of milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC), also called Epoch Time. To put it in perspective, one day contains 86,400,000 milliseconds…

Rather than understanding the concepts of dates and times, computers simply record every point in time since the Epoch time. In Javascript, when the current date is requested, it is then returned as the number of milliseconds elapsed since January 1, 1970 00:00:00.

January 1st, 1970 is when it all began

Javascript enables you to create a Date object initialized at a specific time and date, or simply reflecting the current system time on the computer on which the browser is running.

There are two important things to be aware of when working with the Javascript Date object:

  • When reflecting the date and time from a browser you are completely bound to the user’s computer day and time: if the user did not set the date right on his computer, your Date object will reflect these false settings.
  • Whilst you can read the system date and time set on the user’s computer, and set your own changes inside your Date object according to the date your read from the computer, you cannot change the computer’s system date and time: the user’s system date and time will always remain unchanged.

While working on your own instance of the Date object representing a specific date, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object. But in this article we will focus only on the creation phase of the Date object.

How to construct Date objects ?

A Javascript Date object is created much like any other in Javascript: using the new keyword and some optional arguments to initialize an instance (your own copy) of the Date object.

The syntax for creating your Date() object is as follows:

var myDate = new Date(optional parameters);

Good to know

  • Independent of input format, Javascript will, by default, output dates in full text string format, according to the timezone you are in, for example :

Fri Sep 02 2016 17:24:56 GMT+0200 (CEST)

  • When passing the right arguments to the Date object constructor, you will obtain the representation of the corresponding point in time relative to Epoch Time. However, as stated before, the computer date will be relative to your timezone, and the javascript Date object uses the date set on your computer to output its result.

Once your Date object is created, you have two ways of constructing the date you want to reflect: passing parameters to the instance of the Date object you created, or using the set methods that are native to the Javascript Date object.

Let’s discuss here how you can implement these two methods.

I. Passing parameters to an instance of a Date Object

Javascript offers four ways to create a Date object :

1/ Passing no arguments at all, which will generate the current date, to the millisecond

var today = new Date();// Prints Sun Jun 18 2017 17:24:56 GMT+0200 (CEST)

If no arguments are provided, it creates an object for the current date and time. Passing no argument will display the current date as interpreted by my browser given the settings of my computer.

2/ Passing a number corresponding to the number of milliseconds since Epoch time

var milliseconds = new Date(5000);// Prints Thu Jan 01 1970 01:00:05 GMT+0100 (CET)

Passing the argument 5000 will create a date that represents five seconds past midnight on January 1st, 1970.

3/ Passing a string with a very specific format that will be interpreted as a date

var dateAsString = new Date(dateString);

There are generally 4 types of Javascript string input formats for the Date object :

ISO date (the international standard), written as : “2016–09–02”.

ISO 8601 is the international standard for the representation of dates and times. When passing a string to a Date object in Javascript, it is the preferred date format.

Examples :

→ Complete date (YYYY-MM-DD)

var dateISO = new Date(“2016–03–25”);// Prints Fri Mar 25 2016 01:00:00 GMT+0100 (CET)

→ Year and month (YYYY-MM)

var dateISO = new Date("2016-03");// Prints Tue Mar 01 2016 01:00:00 GMT+0100 (CET)

→ Year (YYYY)

var dateISO = new Date("2016");// Prints Fri Jan 01 2016 01:00:00 GMT+0100 (CET)

→ With added hours, minutes and seconds (YYYY-MM-DDTHH:MM:SS)

var dateISO = new Date("2016-03-25T12:00:00");// Prints Fri Mar 25 2016 13:00:00 GMT+0100 (CET)

Short dates, written as : “03/25/2015” or “2015/03/25”

Short dates are more often passed to the Date object with the “MM/DD/YYYY” syntax, but can also be written as “YYYY/MM/DD”.

→ “MM/DD/YYYY” format

var dateShort = new Date("03/25/2016");// Prints Fri Mar 25 2016 00:00:00 GMT+0100 (CET)

→ “YYYY/MM/DD” format

var dateShort = new Date("2016/03/25");// Prints Fri Mar 25 2016 00:00:00 GMT+0100 (CET)

Good to know

  • Month is written before day in all short date and ISO date formats.
  • If you write month and day numbers without a leading zero (2 instead of 02 for example), they will still be interpreted and output the right date)

Long dates, written as : “Mar 25 2016” or “25 March 2016”.

The most used syntax for long dates string format is “Day Month Year”. However, day, month and year names can be written in any order.

Month names can be written in full (March) or abbreviated (Mar) and are case insensitive.

One more thing to take note of: if you add commas or any kind of separator inside the string, they will be ignored.

var date1 = new Date("3 march 2016");var date2 = new Date("3 MARCH, 2016");var date3 = new Date("2016 3 March");var date4 = new Date("3 2016 mar");var date5 = new Date("March 2016 3");var date6 = new Date("March*2016,3");

// All of the above will print Thu Mar 03 2016 00:00:00 GMT+0100 (CET)

Full date, written as : “Thursday March 03 2016”.

JavaScript will accept date strings in “full JavaScript format”, which is the same format that is used for outputting the content of a Date object.

var dateFull = new Date("Mon Mar 02 2015 00:00:00 GMT+0100 (CET)");// Prints Mon Mar 02 2015 00:00:00 GMT+0100 (CET)

Timezone-related parenthesis like (CET) in our example are optional and will be ignored if erroneous.

Good to know

String parameters and Timezones: be aware

When you pass a string representing a date for example, if no timezone is specified, this date will be converted to match the timezone you are in.In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

Thus, when you pass for example :

var newYear = new Date(“2016”);

Depending on the timezone your are in, the output could vary between December 31 2015 and January 01 2016.

String parameters are converted to numbers by the Date object

When a string is passed as a parameter to the Date object, it is then converted into a number (number of milliseconds since Epoch Time).

If the string format is illegal and not accepted by the Date object, the parameter will be passed as “NaN” (Not a Number) and result in an “Invalid date” error.

4/ Passing every argument in the right order, separated by a comma

var d = new Date(year, month, day [,hour,minute,second,millisecond ]);

All these parameters are integers, each representing a chunk of the full date javascript formatting.

While the first three arguments (year, month and day) are in principle mandatory, Javascript can interpret the date if you pass only the year and month arguments. In that case, the 3rd argument (day) will be interpreted as equal to 1.

The last four arguments (hour, minute, second, millisecond) are optional and taken to 0 if not specified. When one of these four optional arguments is specified, all the other arguments to its left must also be specified.

→ Be careful : If you give the Date object a single argument, that argument will be treated as a millisecond count, not as the first parameter (year).

Let’s review these arguments one by one and see how they can be used as parameters of a Date object:

→ year

Specify the year in full (use 1998 instead of 98 for example). However, be aware that if you use a two-digit date between 0 and 99, 1900 will be added to the integer (98 will become 1998).

→ month

The month parameter is zero-based (contrary to the day parameter). The integer will therefore be comprised between 0 (January) and 11 (December)

→ day

The day parameter represents the day of the month. It begins at 1 (contrary to the month parameter) and the integer will be comprised between 1 and 31.

→ hour

The hour parameter represents the hour of the day on a 24 hours scale. The integer will be comprised between 0 and 23.

→ minute

The minute parameter is on a 60 minutes scale. The integer will be comprised between 0 and 59.

→ second

The second parameter is on a 60 seconds scale. The integer will be comprised between 0 and 59.

→ millisecond

The millisecond parameter is on a 1000 milliseconds scale. The integer will be comprised between 0 and 999.

var theDate = new Date(2016,6,17,21,15,30,0);// Prints Sun Jul 17 2016 21:15:30 GMT+0200 (CEST)

Note that the month number (6) corresponds to July and not June, due to the zero-based structure of the month parameter.

II. Using the “set” methods that set a component’s value within a Date

The Date object’s methods, that can be used on an instance of date, feature set methods for setting specific components of the date. These methods let you set values for a part of the date : years, months, days, hours, minutes, seconds and milliseconds.

Let’s create for example an instance of the Date object that will represent the current date, and review the set methods we can apply to this newly created myDate variable :

var myDate = new Date();// Prints Sat Sep 03 2016 16:22:20 GMT+0200 (CEST)

→ setFullYear()

Sets the year (optionally month and day)

myDate.setFullYear(2001);// Prints Mon Sep 03 2001 16:28:40 GMT+0200 (CEST)

→ setMonth()

Sets the month (0–11)

myDate.setMonth(2);// Prints Thu Mar 03 2016 16:33:48 GMT+0100 (CET)

→ setDate()

Sets the day of the month as a number (1–31)

myDate.setDate(25);// Prints Sun Sep 25 2016 16:22:20 GMT+0200 (CEST)

→ setHours()

Sets the hour (0–23)

myDate.setHours(9);// Prints Sat Sep 03 2016 09:31:23 GMT+0200 (CEST)

→ setMinutes()

Sets the minutes (0–59)

myDate.setMinutes(1);// Prints Sat Sep 03 2016 16:01:02 GMT+0200 (CEST)

→ setSeconds()

Sets the seconds (0–59)

myDate.setSeconds(30);// Prints Sat Sep 03 2016 16:36:30 GMT+0200 (CEST)

→ setMilliseconds():

Sets the milliseconds (0–999)

→ setTime()

Sets the time in milliseconds since January 1, 1970

Conclusion

You have many options at your service to build your own instance of the Date object in Javascript, and even more ways of retrieving and displaying it with native built-in methods.

What can be puzzling when manipulating dates is the management of the different timezones users find themselves in, along with the lack of control on the user’s computer settings.

From blog comments to online orders to booking calendars however, the right use of Date object is one of the most important Javascript components that make for trusted and reliable web applications.

Want to learn more ? Check out my other articles on the basics of JavaScript:

I hope you enjoyed this explanation of Dates in JavaScript.

Feel free to comment and like this article so that others can find it easily on Medium !


Published by HackerNoon on 2017/06/18