Dating in JavaScript
Since we are in Saint Valentine’s day, I was thinking about dating… Not about dating someone, but how to have a date in JavaScript.
There are 4 ways to create a date in JavaScript by using the Date data type:
- Date()
- Date(number)
- Date(number1, number2, number3, number4, number5, number6, number7)
- Date(string)
Date()
Creating a date without passing an argument will create a new Date and Time using the date and time of the browser computer. This type of creation is handy if you want only the current date and/or time for your web page.
var d = new Date(); // Will display current date and time of the browser computer. Console.log(d);
Date(number)
The number argument is the milliseconds of the whole date and time concept. It is simply adding milliseconds to the January 1, 1970 default date.
var d = new Date(86400000); // Will display Thu Jan 01 1970 19:00:00 GMT-0500 (Eastern Standard Time). Console.log(d);
Date(number1, number2, number3, number4, number5, number6, number7)
Numbers 1 through 3 are Year, Month and Day. Numbers 4 through 6 are Hour, Minutes and Seconds. Number 7 will be the Milliseconds. There is also a second form of use Date(number1, number2, number3), were numbers 1 through 3 are Year, Month and Day and the time portion will not be set.
var dt = new Date(2016, 6, 5, 9, 15, 56, 3); // Will display Tue Jul 05 2016 09:15:56 GMT-0400 (Eastern Daylight Time) Console.log(dt); var d = new Date(2016, 6, 5); // Will display Tue Jul 05 2016 00:00:00 GMT-0400 (Eastern Daylight Time) Console.log(d);
If you are wondering why in the previous code the date is not Jun 05 2016, is because JavaScript counts months from zero to eleven. So, January is 0 and December is 11, therefore, 6 is July.
Date(string)
You can also create a Date object in JavaScript using a string. The string must be written in a valid date format that JavaScript can parse as a Date. Some example of formats are:
- YYYY-MM-DD format
- YYYY-MM format
- YYYY format
- YYYY-MM-DDTHH:MM:SS format
- MMM DD YYYY format
- DD MMM YYYY format
- MMM,DD,YYYY format
- DD,MMM,YYYY format
- MM/DD/YYYY format
- YYYY/MM/DD format
- DayOfTheWeek MM DD YYYY HH:MM:SS TimeZone format
The month can be written as a whole, ex. July or as short Jul.
var d1 = new Date("2016-06-05"); // Will display Tue Jul 05 2016 00:00:00 GMT-0400 (Eastern Daylight Time) Console.log(d1); var d2 = new Date("2016-06"); // Will display Tue Jul 01 2016 00:00:00 GMT-0400 (Eastern Daylight Time) Console.log(d2); var d3 = new Date("Jul 5 2016"); // Will display Tue Jul 05 2016 00:00:00 GMT-0400 (Eastern Daylight Time) Console.log(d3);
Conclusion
There are several ways to create dates in JavaScript. Each one is unique and their use will depend on the in’s and out’s of what we are trying to accomplish in our web page.