By Suresh


2009-10-07 11:39:02 8 Comments

How do I get current date in JavaScript?

30 comments

@Waheed 2018-10-04 12:42:32

I thought I would paste what I use for a real date:

function realDate(date){
    return date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getUTCFullYear();
}

var ourdate = realDate(new Date);

@Damjan Pavlica 2016-03-10 16:30:37

The shortest possible.

To get format like "2018-08-03":

let today = new Date().toISOString().slice(0, 10)

console.log(today)

To get format like "8/3/2018":

let today = new Date().toLocaleDateString()

console.log(today)

Also, you can pass locale as argument, for example toLocaleDateString("sr"), etc.

@jafarbtech 2018-05-18 07:27:16

As toISOString() will only return current UTC time , not local time. We have to make a date by using '.toString()' function to get date in yyyy-MM-dd format like

document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('T')[0]);

To get date and time into in yyyy-MM-ddTHH:mm:ss format

document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);

To get date and time into in yyyy-MM-dd HH:mm:ss format

document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0].replace('T',' '));

@Aung Htet 2018-03-10 14:48:28

If you are happy with YYYY-MM-DD format, this will do the job as well.

new Date().toISOString().split('T')[0]

2018-03-10

@Ramesh Rajendran 2018-02-27 07:44:15

You can get by using new Date() to the current browser date in JavaScript.

But currently we have a good plugin for Parse, validate, manipulate, and display dates and times in JavaScript by using moment.js

@RRR 2017-12-12 13:59:32

This may help you

let d = new Date();                      

this.dateField = element(by.xpath('xpath here'));
this.datetField.sendKeys((d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear());

@Blair Anderson 2017-12-01 21:43:24

The Shortest Answer is: new Date().toJSON().slice(0,10)

@METALHEAD 2018-08-23 06:39:01

Best answer...Much better than the marked answer. Thank you.

@Samuel Meddows 2011-02-08 04:42:59

Use new Date() to generate a new Date object containing the current date and time.

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

if(dd<10) {
    dd = '0'+dd
} 

if(mm<10) {
    mm = '0'+mm
} 

today = mm + '/' + dd + '/' + yyyy;
document.write(today);

This will give you today's date in the format of mm/dd/yyyy.

Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.

@lbennet 2013-03-28 23:28:09

how to get hour and minutes

@imin 2013-07-15 15:15:42

thanks for the code.. but what I still don't get it, is the line if(dd<10){dd='0'+dd} ... why < 10? from what I understand from the code is if day's character is less than 2, just add a preceding 0 in front of the day.. but why 10?

@zfm 2013-07-19 06:20:09

@imin: because less than 2 characters means 1 character... and everything under 10 (1 to 9) is 1 character, so we'll have 01, 02, ..., 09

@nnnnnn 2014-04-23 22:36:41

@MounaCheikhna - How could we be in the year 999?

@Mark Micallef 2014-06-11 04:11:34

Swap around the month and date if you're not in north America.

@Niko Bellic 2014-09-18 16:31:47

@MounaCheikhna why are you adding 1900? If we were in the year 999, this would make it 2899 (999 + 1900)

@John K 2015-05-06 21:55:11

I wrapped it in a function for my own use, providing it here > jsfiddle.net/johndkane/cmzppwps

@Xogle 2015-07-09 18:42:30

This is sexy!!! Because you leave it as a date, you can then do date compares, such as today < yesterday.

@Adam Brown 2016-02-16 16:53:40

The new Date.prototype.toLocaleDateString() method is a more flexible solution. It's a part of JavaScript since ECMAScript 5.1 and is well-supported by evergreen browsers. MDN: toLocaleDateString()

@cee 2016-04-11 20:54:13

Today I found a pretty neat trick. ('0' + today.getDate()).slice(-2) This returns the current date always as 2 digits.

@delphirules 2017-03-09 19:16:06

Oh man, twelve lines of code just to get the current date. In Delphi it would be just "formatdatetime('mm/dd/yyyy',now)" . Miss the old times :)

@Sakshi Nagpal 2018-06-24 17:44:30

date.toLocaleDateString('en-GB')

@Yergalem 2017-05-10 19:30:56

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;

} ());

@Cameron Donahue 2017-01-20 12:35:42

A one-line JS solution:

tl;dr

var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];

edge, ff latest, & chrome return todaysDate = "2/7/2017"
"works"* in IE10+

EDIT 2/7/2017

I found out that IE10 and IE Edge do things a bit differently.. go figure. with new Date(Date.now()).toLocaleString() as input,

IE10 returns:

"Tuesday, February 07, 2017 2:58:25 PM"

I could write a big long function and FTFY. But you really ought to use moment.js for this stuff. My script merely cleans this up and gives you the expanded traditional US notation: > todaysDate = "March 06, 2017"

IE EDGE returns:

"‎2‎/‎7‎/‎2017‎ ‎2‎:‎59‎:‎27‎ ‎PM"

Of course it couldn't be that easy. Edge's date string has invisible "•" characters between each visible one. So not only will we now be checking if the first character is a number, but the first 3 characters, since it turns out that any single character in the whole date range will eventually be a dot or a slash at some point. So to keep things simple, just .slice() the first three chars (tiny buffer against future shenanigans) and then check for numbers. It should probably be noted that these invisible dots could potentially persist in your code. I'd maybe dig into that if you've got bigger plans than just printing this string to your view.

∴ updated one-liner:

var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];

That sucks to read. How about:

var dateString = new Date(Date.now()).toLocaleString();
var todaysDate = dateString.slice(0,3).match(/[0-9]/i) ? dateString.split(' ')[0].split(',')[0] : dateString.split(' ')[1] + " " + dateString.split(' ')[2] + " " + dateString.split(' ')[3];

ORIGINAL ANSWER

I've got a one-liner for you:

new Date(Date.now()).toLocaleString().split(', ')[0];

and [1] will give you the time of day.

@roshan 2013-11-03 18:03:16

This works every time:

    var now = new Date();
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear() + "-" + (month) + "-" + (day);
    
    document.write(today);

@WhereDatApp.com 2016-07-18 17:15:00

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale:

2/27/2017, 9:15:41 AM

@Andrew 2017-02-24 21:26:30

Yay, finally...

@Souvik 2017-02-01 11:50:51

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

@Varun Natraaj 2013-09-29 14:13:13

var utc = new Date().toJSON().slice(0,10).replace(/-/g,'/');
document.write(utc);

Use the replace option if you're going to reuse the utc variable, such as new Date(utc), as Firefox and Safari don't recognize a date with dashes.

@Norbert 2014-02-12 09:49:29

Looks to good to be true. Any downsides to this?

@Varun Natraaj 2014-02-12 10:40:24

I dont think so :) Seems pretty straightforward!

@Andy 2014-02-16 07:10:26

toJSON() returns as utc datetime

@Varun Natraaj 2014-02-18 09:08:57

It returns a JSON datetime. toUTCString() returns as utc datetime.

@mickmackusa 2014-06-26 15:13:55

It doesn't consider TimezoneOffset. At my time of testing, I was seeking "now" and I got "yesterday". stackoverflow.com/questions/13646446/…

@Varun Natraaj 2014-06-26 16:17:06

True :) Valid point :)

@Kyle Hotchkiss 2014-08-09 22:19:38

Perfect. This is the cleanest way to do this I'm seeing here. Works well in MomentJS for "Today, Not Now" moment( new Date().toJSON().slice(0, 10) )

@user3374348 2015-05-26 14:14:09

In that case you can use moment().startOf("day")

@user1338062 2015-08-11 06:09:01

I posted a slightly modified answer that takes TimezoneOffset into account: stackoverflow.com/a/31934378/1338062

@Spacemancraig 2015-10-22 17:24:24

Works but I had enclose (new Date()).toJSON().slice(0,10)

@Álvaro González 2015-12-22 17:39:49

.toJSON() includes time zone information; .slice() strips it.

@Varun Natraaj 2016-01-07 19:21:34

.toJSON() gives the current datetime in UTC. Since the question was with respect to current date alone, slice answers it.

@Tân Nguyễn 2016-01-14 10:50:34

Doen't work in IE 7/8

@slier 2016-03-13 09:14:21

how to format this to mm-dd-YY ?

@Max 2016-12-27 17:05:16

You'll need to replace dashes with slashes by adding .replace(/-/g,'/'), so it becomes new Date().toJSON().slice(0,10).replace(/-/g,'/') as FireFox and Safari don't recognize a date with dashes such as "2016-12-27".

@SpYk3HH 2012-02-10 14:33:51

UPDATED!, Scroll Down

If you want something simple pretty to the end user ... Also, fixed a small suffix issue in the first version below. Now properly returns suffix.

var objToday = new Date(),
	weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
	dayOfWeek = weekday[objToday.getDay()],
	domEnder = function() { var a = objToday; if (/1/.test(parseInt((a + "").charAt(0)))) return "th"; a = parseInt((a + "").charAt(1)); return 1 == a ? "st" : 2 == a ? "nd" : 3 == a ? "rd" : "th" }(),
	dayOfMonth = today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,
	months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
	curMonth = months[objToday.getMonth()],
	curYear = objToday.getFullYear(),
	curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
	curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
	curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
	curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;

document.getElementsByTagName('h1')[0].textContent = today;
<h1></h1>

UBBER UPDATE After much procrastination, I've finally GitHubbed and updated this with the final solution I've been using for myself. It's even had some last minute edits to make it sweeter! If you're looking for the old jsFiddle, please see this.

This update comes in 2 flavors, still relatively small, though not as small as my above, original answer. If you want extremely small, go with that.
Also Note: This is still less bloated than moment.js. While moment.js is nice, imo, it has to many secular methods, which require learning moment as if it were a language. Mine here uses the same common format as PHP:date.

Quick Links

Flavor 1 new Date().format(String) My Personal Fav. I know the taboo, but works great on the Date Object. Just be aware of any other mods you may have to the Date Object.

//  use as simple as
new Date().format('m-d-Y h:i:s');   //  07-06-2016 06:38:34

Flavor 2 dateFormat(Date, String) More traditional all-in-one method. Has all the ability of the previous, but is called via method with Date param.

//  use as simple as
dateFormat(new Date(), 'm-d-Y h:i:s');  //  07-06-2016 06:38:34

BONUS Flavor (requires jQuery) $.date(Date, String) This contains much more than just a simple format option. It extends the base Date object and includes methods such as addDays. For more information, please see the Git.

In this mod, the format characters are inspired by PHP:date. For a complete list, please see my README

This mod also has a much longer list of pre-made formats. To use a premade format, simply enter its key name. dateFormat(new Date(), 'pretty-a');

  • 'compound'
    • 'commonLogFormat' == 'd/M/Y:G:i:s'
    • 'exif' == 'Y:m:d G:i:s'
    • 'isoYearWeek' == 'Y\\WW'
    • 'isoYearWeek2' == 'Y-\\WW'
    • 'isoYearWeekDay' == 'Y\\WWj'
    • 'isoYearWeekDay2' == 'Y-\\WW-j'
    • 'mySQL' == 'Y-m-d h:i:s'
    • 'postgreSQL' == 'Y.z'
    • 'postgreSQL2' == 'Yz'
    • 'soap' == 'Y-m-d\\TH:i:s.u'
    • 'soap2' == 'Y-m-d\\TH:i:s.uP'
    • 'unixTimestamp' == '@U'
    • 'xmlrpc' == 'Ymd\\TG:i:s'
    • 'xmlrpcCompact' == 'Ymd\\tGis'
    • 'wddx' == 'Y-n-j\\TG:i:s'
  • 'constants'
    • 'AMERICAN' == 'F j Y'
    • 'AMERICANSHORT' == 'm/d/Y'
    • 'AMERICANSHORTWTIME' == 'm/d/Y h:i:sA'
    • 'ATOM' == 'Y-m-d\\TH:i:sP'
    • 'COOKIE' == 'l d-M-Y H:i:s T'
    • 'EUROPEAN' == 'j F Y'
    • 'EUROPEANSHORT' == 'd.m.Y'
    • 'EUROPEANSHORTWTIME' == 'd.m.Y H:i:s'
    • 'ISO8601' == 'Y-m-d\\TH:i:sO'
    • 'LEGAL' == 'j F Y'
    • 'RFC822' == 'D d M y H:i:s O'
    • 'RFC850' == 'l d-M-y H:i:s T'
    • 'RFC1036' == 'D d M y H:i:s O'
    • 'RFC1123' == 'D d M Y H:i:s O'
    • 'RFC2822' == 'D d M Y H:i:s O'
    • 'RFC3339' == 'Y-m-d\\TH:i:sP'
    • 'RSS' == 'D d M Y H:i:s O'
    • 'W3C' == 'Y-m-d\\TH:i:sP'
  • 'pretty'
    • 'pretty-a' == 'g:i.sA l jS \\o\\f F Y'
    • 'pretty-b' == 'g:iA l jS \\o\\f F Y'
    • 'pretty-c' == 'n/d/Y g:iA'
    • 'pretty-d' == 'n/d/Y'
    • 'pretty-e' == 'F jS - g:ia'
    • 'pretty-f' == 'g:iA'

As you may notice, you can use double \ to escape a character.


@SpYk3HH 2014-02-06 15:32:44

@KamranAhmed Almost 2 years and 40+ votes later, I'd say the effort was worth it. LoL. I've since expanded this class alot personally, but haven't uploaded as I was thinking most people would use that other js date plugin i see recommended, but I guess I should make it more "public" and add it up here.

@Christian Stewart 2014-09-17 22:26:44

moment.js is now the thing you would use these days

@Mike Devenney 2016-11-17 14:05:13

Thumbs up for the effort and light weight!

@user1435707 2017-10-18 14:36:29

Above, there is a typo (that took me awhile to spot), it uses a variable "today" in the line: " dayOfMonth = today + "

@Alex S 2018-01-09 14:56:26

"today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder" - JS is stupid language.

@D.Madu 2018-08-17 09:58:13

nice one. this is good

@Jayant Patil 2016-08-17 08:33:10

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

@Morad 2014-08-16 11:56:12

You can use moment.js: http://momentjs.com/

var m = moment().format("DD/MM/YYYY");

document.write(m);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

@nottinhill 2014-09-11 16:34:24

Best answer, MomentJs looks awesome.

@Dan Dascalescu 2014-10-27 11:15:16

Moment is overkill for just getting the current date.

@Dunc 2017-04-18 14:56:51

Or moment().format("L") to respect the current locale.

@Todd 2018-06-17 13:47:10

@DanDascalescu Actually, the Javascript base specification for DateTime is that bad.

@Marshal 2014-09-02 06:14:35

If you just want a date without time info, use:

var today = new Date();
    today.setHours(0, 0, 0, 0);

document.write(today);

@Inrego 2015-09-30 12:39:00

This seems to be the only answer that actually answers the question. Everyone else answers on how to format a date as string.

@Pawel Gradecki 2017-03-22 10:41:13

++ best answer in this thread

@tkarls 2017-06-26 14:02:48

Indeed. This is the correct answer to the problem.

@Rishabh Marya 2013-06-28 22:32:38

var d = (new Date()).toString().split(' ').splice(1,3).join(' ');

document.write(d)

To break it down into steps:

  1. (new Date()).toString() gives "Fri Jun 28 2013 15:30:18 GMT-0700 (PDT)"

  2. (new Date()).toString().split(' ') divides the above string on each space and returns an array as follows: ["Fri", "Jun", "28", "2013", "15:31:14", "GMT-0700", "(PDT)"]

  3. (new Date()).toString().split(' ').splice(1,3).join(' ') takes the second, third and fourth values from the above array, joins them with spaces, and returns a string "Jun 28 2013"

@panhandel 2013-09-18 06:16:05

I needed a time in 00:00:00 and didn't want to rebuild it manually; step 2 gets me there perfectly. Kudos!

@hyde 2015-03-02 21:42:04

You can save some bytes by doing this: Date().split(' ').splice(1,3).join(' ')

@Zach Saucier 2015-07-17 18:19:49

Thanks for the break down!

@Ron Royston 2016-05-03 22:14:04

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

Just trying to help...

enter image description here

@Jimmy M 2012-02-15 08:48:02

Try this:

var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")

The result will be like

15/2/2012

@user3519897 2016-02-03 12:08:37

new Date().toDateString();

Result:

"Wed Feb 03 2016"

@John Slegers 2016-01-24 20:41:31

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

@Dunaevsky Maxim 2014-07-09 07:01:38

var date = new Date().toLocaleDateString("en-US");

Also, you can call method toLocaleDateString with two parameters:

var date = new Date().toLocaleDateString("en-US", {
    "year": "numeric",
    "month": "numeric"
});

Article on MSDN. More about this method on MDN.

@chris 2016-04-22 16:04:34

Nice, works on Chrome. Unfortunately doesn't work on PhantomJS as of 22/4/2016

@ISONecroMAn 2015-10-31 19:39:27

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

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

@maxagaz 2018-03-04 09:16:01

It would return mistakes, like this 3/4/2018, , better to use new Date().toJSON().slice(0,10).

@Paul Carlton 2018-04-03 19:37:51

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)

@Toucouleur 2015-10-01 16:19:05

new Date().toISOString().slice(0,10); 

would work too

@marverix 2015-10-01 15:25:15

I don't know if it will help anyone, but I'm using this to get today Date object.

new Date( 3600000*Math.floor(Date.now()/3600000) )

@Akhil 2015-08-11 06:31:18

You can checkout this

var today = new Date();
today = parseInt(today.getMonth()+1)+'/'+today.getDate()+'/'+today.getFullYear()+"\nTime : "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds();
document.write(today);

And see the documentation for Date() constructor. link

@user1338062 2015-08-11 06:08:17

Varun's answer does not account for TimezoneOffset. Here is a version that does:

var d = new Date()
new Date(d.getTime() - d.getTimezoneOffset() * 60000).toJSON().slice(0, 10) // 2015-08-11

The TimezoneOffset is minutes, while the Date constructor takes milliseconds, thus the multiplication by 60000.

@Jose Rojas 2015-05-15 14:40:02

You can get the current date call the static method now like this:

var now = Date.now()

reference:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/now

@Perposterer 2017-04-28 20:33:12

This was basically all I needed. var dtToday = new Date(date.now);

Related Questions

Sponsored Content

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5133665 View
  • 6430 Score
  • 69 Answer
  • Tags:   javascript arrays

88 Answered Questions

[SOLVED] How do JavaScript closures work?

20 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2407686 View
  • 2581 Score
  • 20 Answer
  • Tags:   javascript url

25 Answered Questions

53 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

74 Answered Questions

[SOLVED] How to validate an email address in JavaScript?

8 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 565325 View
  • 6142 Score
  • 8 Answer
  • Tags:   java date timezone

36 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

48 Answered Questions

Sponsored Content