How do I get the current date in JavaScript?
64 Answers
My solution uses string literals. Find out more...
// Declare Date as d
var d = new Date()
// Inline formatting of Date
const exampleOne = `${d.getDay()}-${d.getMonth() + 1}-${d.getFullYear()}`
// January is 0 so +1 is required
// With Breaklines and Operators
const exampleTwo = `+++++++++++
With Break Lines and Arithmetic Operators Example
Year on newline: ${d.getFullYear()}
Year minus(-) 30 years: ${d.getFullYear() - 30}
You get the idea...
+++++++++++`
console.log('=============')
console.log(exampleOne)
console.log('=============')
console.log(exampleTwo)
Comments
Date.prototype.toLocalFullDateStringYYYYMMDDHHMMSS = function () {
if (this != null && this != undefined) {
let str = this.getFullYear();
str += "-" + round(this.getMonth() + 1);
str += "-" + round(this.getDate());
str += "T";
str += round(this.getHours());
str += ":" + round(this.getMinutes());
str += ":" + round(this.getSeconds());
return str;
} else {
return this;
}
function round(n){
if(n < 10){
return "0" + n;
}
else return n;
}};
Comments
Important note: do not use: var today = new Date();
But var dateToday = new Date();, for example, as var today does not indicate anything.
1 Comment
Mahyar Mottaghi Zadeh
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
var currentTime = new Date();new Date()returns the current time, not the current date. The distinction matters if you're trying to compare it against another date which doesn't have a time component (ie, is at midnight).