LATEST EDIT: 8/23/19
The date-fns library works much like moment.js but has a WAY smaller footprint. It lets you cherry pick which functions you want to include in your project so you don't have to compile the whole library to format today's date. If a minimal 3rd party lib isn't an option for your project, I endorse the accepted solution by Samuel Meddows up top.
Preserving history below because it helped a few people. But for the record it's pretty hacky and liable to break without warning, as are most of the solutions on this post
EDIT 2/7/2017
A one-line JS solution:
tl;dr
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
edge, ff latest, & chrome return todaysDate = "2/7/2017"
"works"* in IE10+
Explanation
I found out that IE10 and IE Edge do things a bit differently.. go figure.
with new Date(Date.now()).toLocaleString()
as input,
IE10 returns:
"Tuesday, February 07, 2017 2:58:25 PM"
I could write a big long function and FTFY. But you really ought to use moment.js for this stuff. My script merely cleans this up and gives you the expanded traditional US notation: > todaysDate = "March 06, 2017"
IE EDGE returns:
"2/7/2017 2:59:27 PM"
Of course it couldn't be that easy. Edge's date string has invisible "•" characters between each visible one. So not only will we now be checking if the first character is a number, but the first 3 characters, since it turns out that any single character in the whole date range will eventually be a dot or a slash at some point. So to keep things simple, just .slice() the first three chars (tiny buffer against future shenanigans) and then check for numbers. It should probably be noted that these invisible dots could potentially persist in your code. I'd maybe dig into that if you've got bigger plans than just printing this string to your view.
∴ updated one-liner:
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
That sucks to read. How about:
var dateString = new Date(Date.now()).toLocaleString();
var todaysDate = dateString.slice(0,3).match(/[0-9]/i) ? dateString.split(' ')[0].split(',')[0] : dateString.split(' ')[1] + " " + dateString.split(' ')[2] + " " + dateString.split(' ')[3];
ORIGINAL ANSWER
I've got a one-liner for you:
new Date(Date.now()).toLocaleString().split(', ')[0];
and [1]
will give you the time of day.