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!
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
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
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
console.log(today.toISOString()); // '2021-11-22T00:00:00.000Z'
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.