How to get current date in JavaScript
Coderslang: Become a Software Engineer
Posted on November 15, 2022
There are 2 ways you can get current date in JavaScript. You can just create a new Date
object without
any arguments, or you can use the function Date.now
.
So both new Date()
and Date.now()
can be used to get current date in JS.
Let's log the results to the console.
console.log(new Date());
console.log(Date.now());
If the first case, we'll see a date + time in UTC timezone, and with Date.now
we'll get the number of milliseconds
passed after Jan 1, 1970.
2022-01-13T15:19:32.557Z
1642087172563
Both results represent current date in JavaScript and can be easily compared.
A date object can be converted to milliseconds since Jan 1, 1970 by using a getTime
method.
console.log(new Date().getTime()); // 1642087361849
And you can convert milliseconds returned by Date.now()
to a Date object, although it's pretty redundant.
If you just need current date, it's better to call new Date()
without arguments.
console.log(new Date(Date.now())); // 2022-01-13T15:24:55.969Z
Posted on November 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.