How do I get the current date in JavaScript?

JavascriptDateDate Formatting

Javascript Problem Overview


How do I get the current date in JavaScript?

Javascript Solutions


Solution 1 - Javascript

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

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

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

> 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 too many secular methods, which require learning moment as if it were a language. Mine here uses the same common format as PHP: date.

> 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 the 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.


Solution 5 - Javascript

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

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

document.write(today);

Solution 6 - Javascript

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

Solution 7 - Javascript

If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out momentjs. Terrific library - and only 5KB. http://momentjs.com/

Solution 8 - Javascript

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>

Solution 9 - Javascript

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"
});

More about this method on MDN.

Solution 10 - Javascript

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"

Solution 11 - Javascript

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);
    
    console.log(today);

Solution 12 - Javascript

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale: > 2/27/2017, 9:15:41 AM

Solution 13 - Javascript

Most of the other answers are providing the date with time.
If you only need date.

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

Output

[ '2021-02-08', '06:07:44.629Z' ]

If you want it in / format use replaceAll.

new Date().toISOString().split("T")[0].replaceAll("-", "/")

If you want other formats then best to use momentjs.

Solution 14 - Javascript

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

Solution 15 - Javascript

You can use Date.js library which extens Date object, thus you can have .today() method.

Solution 16 - Javascript

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

Solution 17 - Javascript

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.

Solution 18 - Javascript

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

Solution 19 - Javascript

Using JS built in Date.prototype.toLocaleDateString() (more options here MDN docs) :

const options = { month: '2-digit', day: '2-digit', year: 'numeric', };

console.log(new Date().toLocaleDateString('en-US', options)); // mm/dd/yyyy

Update: We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString(), we can pass an object with options:

const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'

Solution 20 - Javascript

new Date().toDateString();

Result:

> "Wed Feb 03 2016"

Solution 21 - Javascript

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',' '));

Solution 22 - Javascript

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

would work too

Solution 23 - Javascript

Try

`${Date()}`.slice(4,15)

console.log( `${Date()}`.slice(4,15) )

We use here standard JS functionalities: template literals, Date object which is cast to string, and slice. This is probably shortest solution which meet OP requirements (no time, only date)

Solution 24 - Javascript

If you want a simple DD/MM/YYYY format, I've just come up with this simple solution, although it doesn't prefix missing zeros.

var d = new Date();
document.write( [d.getDate(), d.getMonth()+1, d.getFullYear()].join('/') );

Solution 25 - Javascript

LATEST EDIT: 8/23/19 The date-fns library works much like moment.js but has a WAY smaller footprint. It lets you cherry pick which functions you want to include in your project so you don't have to compile the whole library to format today's date. If a minimal 3rd party lib isn't an option for your project, I endorse the accepted solution by Samuel Meddows up top.

Preserving history below because it helped a few people. But for the record it's pretty hacky and liable to break without warning, as are most of the solutions on this post

EDIT 2/7/2017 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+

Explanation

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.

Solution 26 - Javascript

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

Get Current Date Month Year in React js

Solution 27 - Javascript

You can use this

<script>
function my_curr_date() {      
    var currentDate = new Date()
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();
    var my_date = month+"-"+day+"-"+year;
    document.getElementById("dateField").value=my_date;    
}
</script>

The HTML is

<body onload='return my_curr_date();'>
    <input type='text' name='dateField' id='dateField' value='' />
</body>

Solution 28 - Javascript

If by "current date" you are thinking about "today", then this trick may work for you:

> new Date(3600000*Math.floor(Date.now()/3600000))
2020-05-07T07:00:00.000Z

This way you are getting today Date instance with time 0:00:00.

The principle of operation is very simple: we take the current timestamp and divide it for 1 day expressed in milliseconds. We will get a fraction. By using Math.floor, we get rid of the fraction, so we get an integer. Now if we multiply it back by one day (again - in milliseconds), we get a date timestamp with the time exactly at the beginning of the day.

> now = Date.now()
1588837459929
> daysInMs = now/3600000
441343.73886916664
> justDays = Math.floor(daysInMs)
441343
> today = justDays*3600000
1588834800000
> new Date(today)
2020-05-07T07:00:00.000Z

Clean and simple.

Solution 29 - Javascript

A straighforward way to pull that off (whilst considering your current time zone it taking advantage of the ISO yyyy-mm-dd format) is:

let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"

Usually, this is a pretty all-purpose compatible date format and you can convert it to pure date value if needed:

Date.parse(d); // 1582044297000

Solution 30 - Javascript

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

Solution 31 - Javascript

This is good to get formatted date

let date = new Date().toLocaleDateString("en", {year:"numeric", day:"2-digit", month:"2-digit"});
console.log(date);

Solution 32 - Javascript

// Try this simple way

const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);

Solution 33 - Javascript

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

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

Solution 34 - Javascript

This does a lot;

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

Where today.getFullYear() gets current year,

today.getMonth()+1 gets current month

and today.getDate() gets today's date. All of this is concatinated with '/'.

Solution 35 - Javascript

So many complicated answers...

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

Enjoy!

Solution 36 - Javascript

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

Solution 37 - Javascript

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

Solution 38 - Javascript

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().

Solution 39 - Javascript

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.

Solution 40 - Javascript

Pretty Print The Date Like This.

> June 1st, 2015 11:36:48 AM

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

Solution 41 - Javascript

If your looking to format into a string.

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

output "time 11:30:53 AM"

Solution 42 - Javascript

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];
};

Solution 43 - Javascript

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

Just trying to help...

enter image description here

Solution 44 - Javascript

If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out date-FNS. Terrific library - much smaller than moment.js and it's function based approach make it much faster then other class based libraries. Provide large number of operations needed over dates.

https://date-fns.org/docs/Getting-Started

Solution 45 - Javascript

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

Solution 46 - Javascript

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

Solution 47 - Javascript

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;

} ());

Solution 48 - Javascript

This answer is for people looking for a date with ISO-8601 like format and with the timezone. It's pure JS 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/

Solution 49 - Javascript

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();

Solution 50 - Javascript

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

new Date();

If you are looking for date formatting and you are anyways 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

Solution 51 - Javascript

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

Date();

Solution 52 - Javascript

My way

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

Solution 53 - Javascript

Have you tried 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

Solution 54 - Javascript

No library needed, timezone taken into consideration.

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

const currentTimezoneOffset = 8; // UTC+8:00 timezone, 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());

Solution 55 - Javascript

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

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

Solution 56 - Javascript

With ability to render in custom format and using 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

Solution 57 - Javascript

My solution uses string literal [Find out more...][1]

// 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)

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Solution 58 - Javascript

Try This and you can adjust date formate 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;

Solution 59 - Javascript

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;
}};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSureshView Question on Stackoverflow
Solution 1 - JavascriptSamuel MeddowsView Answer on Stackoverflow
Solution 2 - JavascriptVarun NatraajView Answer on Stackoverflow
Solution 3 - JavascriptDamian PavlicaView Answer on Stackoverflow
Solution 4 - JavascriptSpYk3HHView Answer on Stackoverflow
Solution 5 - JavascriptMarshalView Answer on Stackoverflow
Solution 6 - JavascriptJimmy MView Answer on Stackoverflow
Solution 7 - Javascriptbenjamin.keenView Answer on Stackoverflow
Solution 8 - JavascriptMoradView Answer on Stackoverflow
Solution 9 - JavascriptDunaevsky MaximView Answer on Stackoverflow
Solution 10 - JavascriptRishabh MaryaView Answer on Stackoverflow
Solution 11 - JavascriptroshanView Answer on Stackoverflow
Solution 12 - JavascriptOded BreinerView Answer on Stackoverflow
Solution 13 - JavascriptShubham ChadokarView Answer on Stackoverflow
Solution 14 - JavascriptAung HtetView Answer on Stackoverflow
Solution 15 - JavascripteomeroffView Answer on Stackoverflow
Solution 16 - JavascriptJose RojasView Answer on Stackoverflow
Solution 17 - Javascriptuser1338062View Answer on Stackoverflow
Solution 18 - JavascriptBlair AndersonView Answer on Stackoverflow
Solution 19 - JavascriptConstantinView Answer on Stackoverflow
Solution 20 - JavascriptIsayevskiy_SergeyView Answer on Stackoverflow
Solution 21 - JavascriptjafarbtechView Answer on Stackoverflow
Solution 22 - JavascriptToucouleurView Answer on Stackoverflow
Solution 23 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 24 - JavascriptPhil RickettsView Answer on Stackoverflow
Solution 25 - JavascriptCamView Answer on Stackoverflow
Solution 26 - JavascriptAkhilView Answer on Stackoverflow
Solution 27 - JavascriptRogerView Answer on Stackoverflow
Solution 28 - JavascriptmarverixView Answer on Stackoverflow
Solution 29 - JavascriptCaiuby FreitasView Answer on Stackoverflow
Solution 30 - JavascriptSouvikView Answer on Stackoverflow
Solution 31 - JavascriptYugandhar ChaudhariView Answer on Stackoverflow
Solution 32 - JavascriptForce BoltView Answer on Stackoverflow
Solution 33 - JavascriptISONecroMAnView Answer on Stackoverflow
Solution 34 - Javascriptanil shresthaView Answer on Stackoverflow
Solution 35 - JavascriptIonicManView Answer on Stackoverflow
Solution 36 - JavascriptJasView Answer on Stackoverflow
Solution 37 - JavascriptJayant PatilView Answer on Stackoverflow
Solution 38 - JavascriptConsta GorganView Answer on Stackoverflow
Solution 39 - JavascriptBrock DavisView Answer on Stackoverflow
Solution 40 - JavascriptAndrewView Answer on Stackoverflow
Solution 41 - JavascriptHarry BoshView Answer on Stackoverflow
Solution 42 - JavascriptFannonView Answer on Stackoverflow
Solution 43 - JavascriptRonnie RoystonView Answer on Stackoverflow
Solution 44 - JavascriptjyotibishtView Answer on Stackoverflow
Solution 45 - JavascriptAndreaView Answer on Stackoverflow
Solution 46 - JavascriptJohn SlegersView Answer on Stackoverflow
Solution 47 - JavascriptYergalemView Answer on Stackoverflow
Solution 48 - Javascriptalain.janinmView Answer on Stackoverflow
Solution 49 - JavascriptSpaceXView Answer on Stackoverflow
Solution 50 - JavascriptagDevView Answer on Stackoverflow
Solution 51 - JavascriptAdrian BartholomewView Answer on Stackoverflow
Solution 52 - JavascriptMansour AlnasserView Answer on Stackoverflow
Solution 53 - JavascriptParking MasterView Answer on Stackoverflow
Solution 54 - JavascriptjchnxuView Answer on Stackoverflow
Solution 55 - JavascriptSarjanWebDevView Answer on Stackoverflow
Solution 56 - JavascriptAlex IvasyuvView Answer on Stackoverflow
Solution 57 - JavascriptJerome HurleyView Answer on Stackoverflow
Solution 58 - JavascriptAshish PathakView Answer on Stackoverflow
Solution 59 - JavascriptYanir CalisarView Answer on Stackoverflow