3044

How do I get the current date in JavaScript?

11
  • 481
    var currentTime = new Date(); Commented Oct 7, 2009 at 11:39
  • 18
    See the documentation for the Date object. It has examples. Commented Oct 7, 2009 at 11:40
  • 5
    this would help you tizag.com/javascriptT/javascriptdate.php Commented Dec 1, 2011 at 4:34
  • 41
    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). Commented Apr 12, 2015 at 1:01
  • 16
    use momentJs, this lib is gold for developers. Commented Dec 22, 2015 at 17:30

64 Answers 64

1 2
3
-1

Try this and you can adjust the date format accordingly:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
    dd = '0' + dd;
}
if (mm < 10) {
    mm = '0' + mm;
}

var myDate = dd + '-' + mm + '-' + yyyy;
Sign up to request clarification or add additional context in comments.

Comments

-1

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

-2
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

-5

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

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
1 2
3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.