How to get the current date with JavaScript

How to get the current date with JavaScript

Photo by Estée Janssens

If you want to get the current date in a format a bit like DD-MM-YYYY or something similar you’ll need to do a bit of work with JavaScript.

First, you’ll need to create a new date object and then call various functions in order to get the components of the date you need.

const​ today ​=​ ​new​ ​Date​();
const​ yyyy ​=​ today​.​getFullYear​();
const​ mm ​=​ today​.​getMonth​()​ ​+​ ​1​;
const​ dd ​=​ today​.​getDate​();
console​.​log​(​`​${​dd​}​-​${​mm​}​-​${​yyyy​}​`​); // 9/9/2020

You might also want to pad the day and month values so they are nicely formatted.

const​ today ​=​ ​new​ ​Date​();
const​ yyyy ​=​ today​.​getFullYear​();
const​ mm ​=​ ​String​(​today​.​getMonth​()​ ​+​ ​1​).​padStart​(​2​,​ ​'0'​);
const​ dd ​=​ ​String​(​today​.​getDate​()).​padStart​(​2​,​ ​'0'​);
console​.​log​(​`​${​dd​}​-​${​mm​}​-​${​yyyy​}​`​); // 09/09/2020

Watch the tutorial for more details.

Follow me on Twitter (@codebubb) for more tutorials👍