A couple of weeks ago, I was writing a little countdown script. I found myself needing to get today's date in vanilla JS, so let me show you how!
The problem
You may be wondering: why not just call the Date()
constructor with no arguments, or use the Date.now()
method? The trouble is that both of these methods also include the current time.
I needed to compare two dates at midnight in UTC. If I'd used new Date()
or Date.now()
, it would have accounted for the hours, minutes, and seconds. My countdown script would have been inaccurate.
Getting today's date
The first thing I did was get today's date string in the format YYYY-MM-DD
. This is a valid ISO date string we can pass into the Date()
constructor. Here's how I did it:
const dateString = new Date().toISOString().slice(0, 10); // '2021-11-22'
Firstly, I called the Date()
constructor. This constructs a Date
object representing the current date and time.
Then I called the toISOString()
method, which returns a string in the format YYYY-MM-DDTHH:mm:ss.sssZ
, according to UTC time. Counting from zero, notice that the first nine characters are YYYY-MM-DD
, which is exactly what we need.
To extract this string, I called the slice()
method. The reason I used 10
for the second index is because this is the index before which we want to stop the slice.
Finally, I assigned the string to the dateString
constant.
Constructing the Date object
Now that we have our date string in YYYY-MM-DD
format, all we need to do is pass it into the Date()
constructor:
const today = new Date(dateString); // Mon Nov 22 2021 00:00:00 GMT+0000 (Greenwich Mean Time)
This leaves us with a Date
object representing midnight today. To verify this, try calling toISOString()
again:
console.log(today.toISOString()); // '2021-11-22T00:00:00.000Z'
A helper function
To make life easier, I've created a helper function you can use:
/**
* Get today's date.
* https://gist.github.com/kieranbarker/2c300d73059697a4417e12bd40cdef75
* @returns {Date} A Date object representing today's date at midnight in UTC.
*/
function getTodaysDate() {
const dateString = new Date().toISOString().slice(0, 10);
return new Date(dateString);
}
Comparing two dates
Next week, I'll show you how I used this technique to get the number of days between today and a date in the future.