DEV Community

Larry
Larry

Posted on

use javascript Date()

Alt Text

How do we get current date using Date() function?

var date = new Date();
console.log("Today's date is:", date);

// Today's date is: Tue Mar 23 2021 23:14:47 GMT+0600 (Bangladesh Standard Time)
Enter fullscreen mode Exit fullscreen mode

Here output will give with GMT and timezone.
If we want to grab specific value then we need to use some method like getMonth(), getDate(), getFullYear() etc...

console.log("Today's date is " + date.getMonth() + "/" + date.getDate() + "/" + date.getFullYear());
// Today's date is 2/23/2021
Enter fullscreen mode Exit fullscreen mode

Here, getMonth() return month index and it is start with 0 that why month says 2 instead of 3 . So, if we get correct month, we have to add 1 with the method.
getDate() return current date.
getFullYear() return 4 digits of current year.

console.log("Today's date is " + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear());
// Today's date is 3/23/2021
Enter fullscreen mode Exit fullscreen mode

Thanks

Top comments (0)