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

8
// Try this simple way const today = new Date(); let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); console.log(date); 
Sign up to request clarification or add additional context in comments.

1 Comment

Answer's are great. But for best practices, please provide an explanation. You only posting code makes the OP and future commers copy and paste your answer without understanding the logic behind the answer. Please provide an answer with some explanation. Thank You!
8

This does a lot:

 var today = new Date(); var date = today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate(); document.write(date);

Where today.getFullYear() gets the current year.

today.getMonth()+1 gets the current month.

And today.getDate() gets today's date.

All of this is concatenated with '/'.

2 Comments

Code-only answers are low-value on Stack Overflow because they do a very poor job of educating/empowering the OP and thousands of future researchers.
Why today.getMonth()+1 ?
8

If you’re looking to format into a string.

statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString(); 

Output: "time 11:30:53 AM"

1 Comment

Why the Date.now()? var x = new Date(Date.now()).toLocaleTimeString(); var y = new Date().toLocaleTimeString(); x === y
7

If you are using jQuery. Try this one liner :

$.datepicker.formatDate('dd/mm/yy', new Date()); 

Here is the convention for formatting the date

  • d - day of month (no leading zero)
  • dd - day of month (two digit)
  • o - day of the year (no leading zeros)
  • oo - day of the year (three digit)
  • D - day name short
  • DD - day name long
  • m - month of year (no leading zero)
  • mm - month of year (two digit)
  • M - month name short
  • MM - month name long
  • y - year (two digit)
  • yy - year (four digit)

Here is the reference for jQuery datepicker

Comments

5
var dateTimeToday = new Date(); var dateToday = new Date( dateTimeToday.getFullYear(), (dateTimeToday.getMonth() + 1) /*Jan = 0! */, dateTimeToday.getDate(), 0, 0, 0, 0); 

3 Comments

Do we really need another answer like that?
I did not find this method in any of the answers so added it
This is a duplicate of this earlier posted and higher voted answer: stackoverflow.com/a/9290264/2943403
5

What's the big deal with this.. The cleanest way to do this is

var currentDate=new Date().toLocaleString().slice(0,10);

2 Comments

It would return mistakes, like this 3/4/2018, , better to use new Date().toJSON().slice(0,10).
This is perfect for simply getting a date for view or for info on console log or for UI. Better for me without the .slice(0,10)
5

So many complicated answers...

Just use new Date() and if you need it as a string, simply use new Date().toISOString()

Enjoy!

Comments

5

In Australia, I prefer to get DD/MM/YYYY using this

(new Date()).toISOString().slice(0, 10).split("-").reverse().join("/") 

2 Comments

Actually returns DD/MM/YYYY , without any details or unwanted info.
perfect what I wanted
4

Pretty Print The Date Like This.

June 1st, 2015 11:36:48 AM

https://gist.github.com/Gerst20051/7d72693f722bbb0f6b58

Comments

4

This may help you

var date = new Date(); console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear()); 

This will print current date in dd/MM/yyyy format

Comments

4

TL;DR

Most of the answers found here are correct only if you need the current time that's on your local machine (client) which is a source that often cannot be considered reliable (it will probably differ from another system).

Reliable sources are:

  • Web server's clock (but make sure that it's updated)
  • Time APIs & CDNs

Details

A method called on the Date instance will return a value based on the local time of your machine.

Further details can be found in "MDN web docs": JavaScript Date object.

For your convenience, I've added a relevant note from their docs:

(...) the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

Another source mentioning this is: JavaScript date and time object

it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different times from the one created on your own computer.

Some reliable sources that you can use are:

But if accuracy is not important for your use case or if you simply need the date to be relative to local machine's time then you can safely use Javascript's Date basic methods like Date.now().

Comments

3

I think this is an old question but the easiest way would be the following:

var date = new Date(); var TimeStamp = date.toLocaleString(); function CurrentTime(){ alert(TimeStamp); } 

This will grab the current time, pass it to a string based on location and then you can call the function CurrentTime to display the time. This would be, to me, the most effective way to get a time stamp for something.

1 Comment

This will return data+time, eg. '2018-4-6 16:20:22', and the question is how to get date only.
3

This is my current favorite, because it's both flexible and modular. It's a collection of (at least) three simple functions:

/** * Returns an array with date / time information * Starts with year at index 0 up to index 6 for milliseconds * * @param {Date} date date object. If falsy, will take current time. * @returns {[]} */ getDateArray = function(date) { date = date || new Date(); return [ date.getFullYear(), exports.pad(date.getMonth()+1, 2), exports.pad(date.getDate(), 2), exports.pad(date.getHours(), 2), exports.pad(date.getMinutes(), 2), exports.pad(date.getSeconds(), 2), exports.pad(date.getMilliseconds(), 2) ]; }; 

Here's the pad function:

 /** * Pad a number with n digits * * @param {number} number number to pad * @param {number} digits number of total digits * @returns {string} */ exports.pad = function pad(number, digits) { return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number; }; 

Finally I can either build my date string by hand, or use a simple functions to do it for me:

/** * Returns nicely formatted date-time * @example 2015-02-10 16:01:12 * * @param {object} date * @returns {string} */ exports.niceDate = function(date) { var d = exports.getDateArray(date); return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5]; }; /** * Returns a formatted date-time, optimized for machines * @example 2015-02-10_16-00-08 * * @param {object} date * @returns {string} */ exports.roboDate = function(date) { var d = exports.getDateArray(date); return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5]; }; 

Comments

2

The basics

If you're happy with the format Sun Jan 24 2016 21:23:07 GMT+0100 (CET), you could just use this code :

var today = new Date(); 

Date.prototype.toLocaleDateString()

If you want to format your output, consider using Date.prototype.toLocaleDateString() :

var today = new Date().toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); 

If you executed that code today (january 24ᵗʰ, 2016) on a modern browser, it would produce the string Sonntag, 24. Januar 2016. Older browsers may generate a different result, though, as eg. IE<11 doesn't support locales or options arguments.

Going custom

If Date.prototype.toLocaleDateString() isn't flexible enough to fulfill whatever need you may have, you might want to consider creating a custom Date object that looks like this :

var DateObject = (function() { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var date = function(str) { this.set(str); }; date.prototype = { set : function(str) { var dateDef = str ? new Date(str) : new Date(); this.day = dateDef.getDate(); this.dayPadded = (this.day < 10) ? ("0" + this.day) : "" + this.day; this.month = dateDef.getMonth() + 1; this.monthPadded = (this.month < 10) ? ("0" + this.month) : "" + this.month; this.monthName = monthNames[this.month - 1]; this.year = dateDef.getFullYear(); } }; return date; })(); 

If you included that code and executed new DateObject() today (january 24ᵗʰ, 2016), it would produce an object with the following properties :

day: 24 dayPadded: "24" month: 1 monthPadded: "01" monthName: "January" year: 2016 

Comments

2

2.39KB minified. One file. https://github.com/rhroyston/clock-js

Just trying to help...

enter image description here

Comments

2

If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out date-FNS.

It is a terrific library and is much smaller than Moment.js. It's a function-based approach that makes it much faster than other class-based libraries. It provides a large number of operations needed over dates.

Comments

1
(function() { var d = new Date(); return new Date(d - d % 86400000); })() 

3 Comments

Where did 86400000 come from?
It's the number of milliseconds in a day: 60secs x 60mins x 24hours x 1000 - you'd probably recognize it too if you've had to mess a lot with dates in JavaScript...
The point is: There should be an explanation with every answer (in the answer) on Stack Overflow.
1

You can use my DATE API given below for everyday use of date formatting along with getting current date, yesterday etc. How to use e.g.

 var dt = new Date(); /// ANY DATE YOU WANT -- dt = new Date(""July 21, 1983 01:15:00"") dateObj = dt.getFormattedDate(); alert( dateObj.isToday() ); alert( dateObj.todayDay() ); alert( dateObj.monthNameDayYear() ); 

(function () { fnDateProcessor = function () { var that = this; return { yyyymmdd: function (separator) { var fdate = this.formatDate(true, true) , separator = separator ? separator : "-"; return fdate.year + separator + fdate.month + separator + fdate.day; }, monthNameDayYear: function () { var fdate = this.formatDate(true, true); return fdate.monthName + " " + fdate.day + ", " + fdate.year; }, ddmmyyyy: function (separator) { var fdate = this.formatDate(true, true) , separator = separator ? separator : "/"; return fdate.day + separator + fdate.month + separator + fdate.year; }, meridianTime: function () { var fdate = this.formatDate(); return fdate.hour + ":" + fdate.minute + " " + fdate.meridian; }, monthDay: function (separator) { var fdate = this.formatDate(); separator = checkSeparator(separator); return fdate.monthName.substring(0, 3) + separator + fdate.day; }, weekMonthDayYear: function () { var fdate = this.formatDate(); //separator = checkSeparator(separator); return fdate.weekDay + " " + fdate.monthName.substring(0, 3) + fdate.day + " ," + fdate.year; }, timeZoneInclusive: function () { return new Date(that); }, todayDay: function () { return new Date().getDate(); }, todayMonth: function () { return new Date().getMonth() + 1; }, dateDay: function () { return this.formatDate().day; }, dateMonth: function () { return this.formatDate().month; }, isToday: function () { return this.sameDate(new Date()); }, isYesterday: function () { d = new Date(); d.setDate(d.getDate() - 1); return this.sameDate(d); }, formatDate: function () { var zeroPaddedMnth = true, zeroPaddedDay = false, zeroPaddedHr = false, zeroPaddedMin = true; // Possible to take Options arg that overide / merge to defaults var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var day = getFormattedDay(that.getDate(), zeroPaddedDay); var monthIndex = that.getMonth(); var month = getFormattedMonth(monthIndex + 1, zeroPaddedMnth); var year = that.getFullYear(); var wkDay = that.getDay(); var hour = getFormattedHour(that.getHours(), zeroPaddedHr); var minute = getFormattedMinute(that.getMinutes(), zeroPaddedMin); var meridian = getMeridian(that.getHours()); return { "day": day, "monthName": monthNames[monthIndex], "month": month, "weekDay": weekDays[wkDay], "year": year, "hour": hour, "minute": minute, "meridian": meridian }; }, compareDate: function (d2) { /// validates if caller is less than argument d2 = _isString(d2) ? new Date(d2) : d2; return !this.sameDate(d2) && typeof d2 != "number" ? that < d2 : false; }, sameDate: function (d) { return that.getFullYear() === d.getFullYear() && that.getDate() === d.getDate() && that.getMonth() === d.getMonth(); }, dateAfter: function (separator) { var fdate = this.formatDate(); var separator = separator ? separator : "-"; return fdate.year + separator + fdate.month + separator + (fdate.day + 1); } }; }; function _isString(obj) { var toString = Object.prototype.toString; return toString.call(obj) == '[object String]'; } function checkSeparator(separator) { // NOT GENERIC ... NEEDS REVISION switch (separator) { case " ": sep = separator; break; case ",": sep = " ,"; break; default: sep = " "; break; } return sep; } function getFormattedHour(h, zeroPadded) { h = h % 12; h = h ? h : 12; // 12 instead of 00 return zeroPadded ? addZero(h) : h; } function getFormattedMinute(m, zeroPadded) { return zeroPadded ? addZero(m) : m; } function getFormattedDay(dd, zeroPadded) { return zeroPadded ? addZero(dd) : dd; } function getFormattedMonth(mm, zeroPadded) { return zeroPadded ? addZero(mm) : mm; } function getMeridian(hr) { return hr >= 12 ? 'PM' : 'AM'; } function addZero(i) { if (i < 10) { i = "0" + i; } return i; } Date.prototype.getFormattedDate = fnDateProcessor; } ()); 

Comments

1

Try Date.js

Milliseconds

date.js.millisecond(); // 0.00 

Seconds

date.js.second(); // 58 

Minutes

date.js.minute(); // 31 

Hours

date.js.hour(); // 6 (PM) 

Days

date.js.day(); // Monday 

Weeks

date.js.week(); // (Week Of the Month / WOM) => 2 

Month

date.js.month(); // (Month) => November 

TLM (Three-Letter-Month)

date.js.tlmonth(); // (Month) => Dec 

Year

date.js.year(); // (Year / String: "") => "2021" 

Season

date.js.season(); // (Fall / Season: seasons) => "fall" 

Current Time in AM/PM

date.js.time(); // (Time / Zone: "PDT/EDT etc.") => 10:04 AM 

2 Comments

Not autumn?
It’s supposed to be in human readable form. You can change that though by using data.js.season() == “fall” ? “autumn” : date.js.season()
1

To get just the date, then it is built in to JavaScript:

new Date(); 

If you are looking for date formatting and you are anyway using the Kendo jQuery UI library for your site, then I suggest using the built-in Kendo function:

kendo.toString(new Date(), "yyMMdd"); // Or any other typical date format 

For a full list of supported formats, see here.

Comments

1

This answer is for people looking for a date with a ISO-8601-like format and with the time zone.

It's pure JavaScript for those who don't want to include any date library.

var date = new Date(); var timeZone = date.toString(); // Get timezone ('GMT+0200') var timeZoneIndex = timeZone.indexOf('GMT'); // Cut optional string after timezone ('(heure de Paris)') var optionalTimeZoneIndex = timeZone.indexOf('('); if(optionalTimeZoneIndex != -1){ timeZone = timeZone.substring(timeZoneIndex, optionalTimeZoneIndex); } else{ timeZone = timeZone.substring(timeZoneIndex); } // Get date with JSON format ('2019-01-23T16:28:27.000Z') var formattedDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON(); // Cut ms formattedDate = formattedDate.substring(0,formattedDate.indexOf('.')); // Add timezone formattedDate = formattedDate + ' ' + timeZone; console.log(formattedDate); 

Print something like this in the console:

2019-01-23T17:12:52 GMT+0100

JSFiddle: https://jsfiddle.net/n9mszhjc/4/

Comments

1

You may want to automatically retrieve the browser's locale name and pass it as the first argument of toLocaleString(), so that you can pass other options:

// Get locale name function getLang() { if (navigator.languages != undefined) return navigator.languages[0]; return navigator.language; } // Get the current datetime with format yyyy-MM-ddThhmmss const time = new Date().toLocaleString(getLang(), { hour12: false , year: 'numeric', month: '2-digit', day: '2-digit', hour: "numeric", minute: "numeric", second: "numeric" }).replaceAll('/', '-').replaceAll(':', '').replaceAll(' ', 'T') console.log("locale:", getLang()) console.log(time)

The result may looks like:

locale: zh-TW 2022-09-13T171642 

When you change your browser's locale setting, the time and date (if needed) will change too.

Comments

1

This is only 2 lines.

let date = new Date().toLocaleDateString() .split("/") .map((d) => (d.length <= 1 ? "0" + d : d)); let newDate = `${date[1]}/${date[0]}/${date[2]}`; console.log(newDate); // => dd/mm/yyyy 

Comments

1

The most flexible method that provides various formatting, is using Date.prototype.toLocaleDateString() (since ECMAScript 5.1):

For example:

const date = new Date(); // US English uses month-day-year order console.log(date.toLocaleDateString("en-US")); // "12/20/2012" // British English uses day-month-year order console.log(date.toLocaleDateString("en-GB")); // "20/12/2012" 

For more formats, check MDN Docs

In additions toLocaleDateString has an options argument that allow customization for those formats.

Comments

0

If you only require the string representation, then simply use:

Date(); 

Comments

0

For anyone looking for a date format like this 09-Apr-2020

function getDate(){ var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = months[today.getMonth()]; var yyyy = today.getFullYear(); today = dd + "-" + mm + "-" + yyyy; return today; } getDate(); 

Comments

0

My way

let dateString = new Date().toLocaleString().split(',').find(() => true); 

Comments

0

A library is not needed, and the time zone is taken into consideration.

Because sometimes you will need to calculate it on the server. This can be server time zone independent.

const currentTimezoneOffset = 8; // UTC+8:00 time zone, change it Date.prototype.yyyymmdd = function() { return [ this.getFullYear(), (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based this.getDate().toString().padStart(2, '0') ].join('-'); }; function getTodayDateStr() { const d = new Date(); // console.log(d); const d2 = new Date(d.getTime() + (d.getTimezoneOffset() + currentTimezoneOffset * 60) * 60 * 1000); // console.log(d2, d2.yyyymmdd()); return d2.yyyymmdd(); } console.log(getTodayDateStr());

Comments

0

With the ability to render in a custom format and using the month name in different locales:

const locale = 'en-us'; const d = new Date(date); const day = d.getDate(); const month = d.toLocaleString(locale, { month: 'long' }); const year = d.getFullYear(); const time = d.toLocaleString(locale, { hour12: false, hour: 'numeric', minute: 'numeric'}); return `${month} ${day}, ${year} @ ${time}`; // May 5, 2019 @ 23:41 

Comments

0

With the upcoming Temporal API (stage 3), you can use Temporal.PlainDateTime.

For example, for the current date and time in the ISO 8601 calendar you can use the plainDateTimeISO method on Temporal.Now

const datetime = Temporal.Now.plainDateTimeISO(); console.log(datetime.toString()); 

Similarly, for only the date you can use Temporal.PlainDate.

const date = Temporal.Now.plainDateISO(); console.log(date.toString()); 

And similarly for only the time you can use Temporal.PlainTime.

const time = Temporal.Now.plainTimeISO(); console.log(time.toString()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.