Date & Time
- new Date()
-
Without arguments – create a Date object for the current date and time:
let now = new Date(); alert( now ); // shows current date/time like this way - Sun Jan 20 2019 03:07:30 GMT+0000 (Greenwich Mean Time)
JavaScript Date Input
There are generally 3 types of JavaScript date input formats:
Type | Example |
---|---|
ISO Date | "2015-03-25" (The International Standard) |
Short Date | "03/25/2015" |
Long Date | "Mar 25 2015" or "25 Mar 2015" |
The other formats are not so well defined and might be browser specific.
Date Input - Parsing Dates
If you have a valid date string, you can use the Date.parse()
method to convert it to milliseconds.
Date.parse()
returns the number of milliseconds between the date and January 1, 1970:
Method | Description |
---|---|
getFullYear() | Get the year as a four digit number (yyyy) |
getMonth() | Get the month as a number (0-11) |
getDate() | Get the day as a number (1-31) |
getHours() | Get the hour (0-23) |
getMinutes() | Get the minute (0-59) |
getSeconds() | Get the second (0-59) |
getMilliseconds() | Get the millisecond (0-999) |
getTime() | Get the time (milliseconds since January 1, 1970) |
getDay() | Get the weekday as a number (0-6) |
Date.now() | Get the time. ECMAScript 5. |
// Initialize a new birthday instance const birthday = new Date(1980, 6, 31);
Now we can use all our methods to get each date component, from year to millisecond.
birthday.getFullYear(); // 1980 birthday.getMonth(); // 6 birthday.getDate(); // 31 birthday.getDay(); // 4 birthday.getHours(); // 0 birthday.getMinutes(); // 0 birthday.getSeconds(); // 0 birthday.getMilliseconds(); // 0 birthday.getTime(); // 333849600000 (for GMT)
Sometimes it may be necessary to extract only part of a date, and the built-in get methods are the tool you will use to achieve this.
For an example of this, we can test the current date against the day and month of October 3rd to see whether it's October 3rd or not.
// Get today's date const today = new Date(); // Compare today with October 3rd if (today.getDate() === 3 && today.getMonth() === 9) { console.log("It's October 3rd."); } else { console.log("It's not October 3rd."); } Output It's not October 3rd.
Since, at the time of writing, it's not October 3rd, the console reflects that.
Date Methods with UTC
The get methods discussed above retrieve the date components based on the user's local timezone settings. For increased control over the dates and times, you can use the getUTC methods, which are exactly the same as the get methods, except they calculate the time based on the UTC (Coordinated Universal Time) standard. Below is a table of the UTC methods for the JavaScript Date object.
Date/Time | Method | Range | Example |
---|---|---|---|
Year | getUTCFullYear() |
YYYY | 1970 |
Month | getUTCMonth() |
0-11 | 0 = January |
Day (of the month) | getUTCDate() |
1-31 | 1 = 1st of the month |
Day (of the week) | getUTCDay() |
0-6 | 0 = Sunday |
Hour | getUTCHours() |
0-23 | 0 = midnight |
Minute | getUTCMinutes() |
0-59 | |
Second | getUTCSeconds() |
0-59 | |
Millisecond | getUTCMilliseconds() |
0-999 |
To test the difference between local and UTC get methods, we can run the following code.
// Assign current time to a variable const now = new Date(); // Print local and UTC timezones console.log(now.getHours()); console.log(now.getUTCHours());
Although GMT and UTC share the same current time in practice, there is a basic difference between the two:
- GMT is a time zone officially used in some European and African countries. The time can be displayed using both the 24-hour format (0 - 24) or the 12-hour format (1 - 12 am/pm).
- UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or territory officially uses UTC as a local time.
JavaScript Stores Dates as Milliseconds
JavaScript stores dates as number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated).
Timestamps
Get a timestamp (number of milliseconds since Jan 1st 1970 UTC) using a date instance’s getTime
and Date.now()
method:
const nowTimestamp = new Date().getTime(); console.log(nowTimestamp); // 1548004682142
const nowTimestamp = Date.now(); console.log(nowTimestamp); // 1548004682142
let date = new Date(); alert(date); // Sun Jan 20 2019 18:45:23 GMT+0000 (Greenwich Mean Time) alert(+date); // 1548009962439 for adding + sign it converts to millisecond
Timestamps are useful to easily calculate the difference in milliseconds between two dates. For example, here we get the difference in milliseconds between Feb 3rd 1996 and Jan 1 1970:
const diff = new Date("1995-02-03").getTime() - new Date(0).getTime();
Human Readable Strings
const now = new Date(); console.log(now.toDateString()); // Wed Dec 06 2017 console.log(now.toTimeString()); // 19:23:42 GMT-0800 (PST) console.log(now.toLocaleDateString()); // 12/6/2017 console.log(now.toLocaleString()); // 12/6/2017, 7:20:28 PM console.log(now.toLocaleTimeString()); // 7:20:51 PM console.log(now.toUTCString()); // Thu, 07 Dec 2017 03:21:14 GMT
Adding/Subtracting Time
Using a combination of the get and set methods, you can add to or subtract from the date/time components of a date instance. Here for example, we add 15 minutes to the current time:
const now = new Date(); console.log(now.toLocaleTimeString()); // 7:47:53 PM now.setMinutes(now.getMinutes() + 15); console.log(now.toLocaleTimeString()); // 8:02:53 PM
Colored clock with setInterval
<style> .hour { color: red } .min { color: green } .sec { color: blue } </style> <div id="clock"> <span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span> </div> <script> let timerId; function update() { let clock = document.getElementById('clock'); let date = new Date(); let hours = date.getHours(); if (hours < 10) hours = '0' + hours; clock.children[0].innerHTML = hours; let minutes = date.getMinutes(); if (minutes < 10) minutes = '0' + minutes; clock.children[1].innerHTML = minutes; let seconds = date.getSeconds(); if (seconds < 10) seconds = '0' + seconds; clock.children[2].innerHTML = seconds; } function clockStart() { timerId = setInterval(update, 1000); update(); // <-- start right now, don't wait 1 second till the first setInterval works } function clockStop() { clearInterval(timerId); } clockStart(); </script> <!-- click on this button calls clockStart() --> <input type="button" onclick="clockStart()" value="Start"> <!-- click on this button calls clockStop() --> <input type="button" onclick="clockStop()" value="Stop">
A Date object offers several methods to check its value. These all depends on the current timezone of the computer:
const date = new Date('July 22, 2018 07:22:13') date.getDate() //22 date.getDay() //0 (0 means sunday, 1 means monday..) date.getFullYear() //2018 date.getMonth() //6 (starts from 0) date.getHours() //7 date.getMinutes() //22 date.getSeconds() //13 date.getMilliseconds() //0 (not specified) date.getTime() //1532236933000 date.getTimezoneOffset() //-120 (will vary depending on where you are and when you check - this is CET during the summer). Returns the timezone difference expressed in minutes
The Internationalization API
The Internationalization API, well supported in modern browsers (notable exception: UC Browser), allows you to translate dates.
It’s exposed by the Intl object, which also helps localizing numbers, strings and currencies.
// "12/22/2017" const date = new Date('July 22, 2018 07:22:13') new Intl.DateTimeFormat().format(date) //"22/07/2018" in my locale
Format a date according to a different locale:
new Intl.DateTimeFormat('en-US').format(date) //"7/22/2018"
Intl.DateTimeFormat
method takes an optional parameter that lets you customize the output. To also display hours, minutes and seconds:
const options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' } new Intl.DateTimeFormat('en-US', options).format(date) //"7/22/2018, 7:22:13 AM" new Intl.DateTimeFormat('it-IT', options2).format(date) //"22/7/2018, 07:22:13"
COMPARE TWO DATES
You can calculate the difference between two dates using Date.getTime()
:
const date1 = new Date('July 10, 2018 07:22:13') const date2 = new Date('July 22, 2018 07:22:13') const diff = date2.getTime() - date1.getTime() //difference in milliseconds
In the same way you can check if two dates are equal:
const date1 = new Date('July 10, 2018 07:22:13') const date2 = new Date('July 10, 2018 07:22:13') if (date2.getTime() === date1.getTime()) { //dates are equal }
getTime()
returns the number of milliseconds, so you need to factor in time in the comparison. July 10, 2018 07:22:13 is not equal to new July 10, 2018. In this case you can use setHours(0, 0, 0, 0)
to reset the time.
Calculating the Difference between Two Known Dates
Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime()
. Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):
Date.daysBetween = function( date1, date2 ) { //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; // Convert back to days and return return Math.round(difference_ms/one_day); } //Set the two dates var y2k = new Date(2000, 0, 1); var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate()); var today= new Date(); //displays 726 console.log( 'Days since ' + Jan1st2010.toLocaleDateString() + ': ' + Date.daysBetween(Jan1st2010, today));
The rounding is optional, depending on whether you want partial days or not.
Converting Milliseconds to other Intervals
As long as you can calculate the number of milliseconds in an interval, you can come up with a number by dividing the total number of milliseconds by the number of milliseconds in the desired interval. What's more, we can apply the modulus (%) operator to strip out that value to determine the next larger interval. The key is to always go from the smallest interval - milliseconds - to the largest - days:
Date.daysBetween = function( date1, date2 ) { //Get 1 day in milliseconds var one_day=1000*60*60*24; // Convert both dates to milliseconds var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); // Calculate the difference in milliseconds var difference_ms = date2_ms - date1_ms; //take out milliseconds difference_ms = difference_ms/1000; var seconds = Math.floor(difference_ms % 60); difference_ms = difference_ms/60; var minutes = Math.floor(difference_ms % 60); difference_ms = difference_ms/60; var hours = Math.floor(difference_ms % 24); var days = Math.floor(difference_ms/24); return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds'; } //Set the two dates var y2k = new Date(2000, 0, 1); var Jan1st2010 = new Date(y2k.getYear() + 10, y2k.getMonth(), y2k.getDate()); var today= new Date(); //displays "Days from Wed Jan 01 0110 00:00:00 GMT-0500 (Eastern Standard Time) to Tue Dec 27 2011 12:14:02 GMT-0500 (Eastern Standard Time): 694686 days, 12 hours, 14 minutes, and 2 seconds" console.log('Days from ' + Jan1st2010 + ' to ' + today + ': ' + Date.daysBetween(Jan1st2010, today));
A Simple dateDiff() Function
There is no reason to write a function for each date/time interval; one function can contain all of the required intervals and return the correct value for the one we want. In the following function, the datepart argument tells it what interval we are after, where 'w' is a week, 'd' a day, 'h' hours, 'n' for minutes, and 's' for seconds:
// datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's' Date.dateDiff = function(datepart, fromdate, todate) { datepart = datepart.toLowerCase(); var diff = todate - fromdate; var divideBy = { w:604800000, d:86400000, h:3600000, n:60000, s:1000 }; return Math.floor( diff/divideBy[datepart]); } //Set the two dates var y2k = new Date(2000, 0, 1); var today= new Date(); console.log('Weeks since the new millenium: ' + Date.dateDiff('w', y2k, today)); //displays 994
Create an array of Dates between start date and end date in JavaScript
var startDate = new Date("2017-10-01"); //YYYY-MM-DD var endDate = new Date("2017-10-07"); //YYYY-MM-DD var getDateArray = function(start, end) { var arr = new Array(); var dt = new Date(start); while (dt <= end) { arr.push(new Date(dt)); dt.setDate(dt.getDate() + 1); } return arr; } var dateArr = getDateArray(startDate, endDate); // Output document.write("<p>Start Date: " + startDate + "</p>"); document.write("<p>End Date: " + endDate + "</p>"); document.write("<p>Date Array</p>") for (var i = 0; i < dateArr.length; i++) { document.write("<p>" + dateArr[i] + "</p>"); }
Start Date: Sun Oct 01 2017 05:30:00 GMT+0530 (IST) End Date: Sat Oct 07 2017 05:30:00 GMT+0530 (IST) Date Array Sun Oct 01 2017 05:30:00 GMT+0530 (IST) Mon Oct 02 2017 05:30:00 GMT+0530 (IST) Tue Oct 03 2017 05:30:00 GMT+0530 (IST) Wed Oct 04 2017 05:30:00 GMT+0530 (IST) Thu Oct 05 2017 05:30:00 GMT+0530 (IST) Fri Oct 06 2017 05:30:00 GMT+0530 (IST) Sat Oct 07 2017 05:30:00 GMT+0530 (IST)
Returns an array of dates between the two dates
// Returns an array of dates between the two dates var getDates = function(startDate, endDate) { var dates = [], currentDate = startDate, addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date; }; while (currentDate <= endDate) { dates.push(currentDate); currentDate = addDays.call(currentDate, 1); } return dates; }; // Usage var dates = getDates(new Date(2013,11,22), new Date(2013,11,25)); dates.forEach(function(date) { alert(date); });
Deserializing JSON Strings as JavaScript Date Objects
const dateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/; function reviver(key, value) { if (typeof value === "string" && dateFormat.test(value)) { return new Date(value); } return value; } const text = '{ "date": "2016-04-26T18:09:16Z" }'; const obj = JSON.parse(text, reviver); console.log(typeof obj.date); // "object"
All about dates - MDN
- Be careful with the month/day position, or you might end up with the month being misinterpreted as the day.
- JavaScript, without any information about the timezone, will consider the date as UTC, and will automatically perform a conversion to the current computer timezone.
- passing no parameters, creates a Date object that represents “now”
- passing a number, which represents the milliseconds from 1 Jan 1970 00:00 GMT
- If you call just Date() without the new keyword, you’ll get a string instead of a Date object.
- Months in JS start from 0-11. Also months wrap around. So if you set month to 13, it'll be set to 1 or February.
- Day(or weekday) is between 0-6 starting with Sunday.