3044

How do I get the current date in JavaScript?

Rob Bednark
28.8k28 gold badges90 silver badges131 bronze badges
asked Oct 7, 2009 at 11:39
11
  • 480
    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
3464

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.

answered Feb 8, 2011 at 4:42
Sign up to request clarification or add additional context in comments.

13 Comments

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?
@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
@MounaCheikhna - How could we be in the year 999?
Swap around the month and date if you're not in north America.
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()
|
547

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.

Max
1,48015 silver badges26 bronze badges
answered Sep 29, 2013 at 14:13

13 Comments

I dont think so :) Seems pretty straightforward!
toJSON() returns as utc datetime
It returns a JSON datetime. toUTCString() returns as utc datetime.
It doesn't consider TimezoneOffset. At my time of testing, I was seeking "now" and I got "yesterday". stackoverflow.com/questions/13646446/…
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) )
|
479

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.

answered Mar 10, 2016 at 16:30

3 Comments

This still fails due to time zone shift.
Your second answer is the best.
Note that this returns the day at UTC+0, but not the local day.
283

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.

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


Jerold Joel
2611 gold badge10 silver badges23 bronze badges
answered Feb 10, 2012 at 14:33

5 Comments

@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.
moment.js is now the thing you would use these days
Above, there is a typo (that took me awhile to spot), it uses a variable "today" in the line: " dayOfMonth = today + "
"today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder" - JS is stupid language.
Its just 39 past noon and it prints 12:39 am.
235

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

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

Michael
5251 gold badge11 silver badges30 bronze badges
answered Sep 2, 2014 at 6:14

4 Comments

This seems to be the only answer that actually answers the question. Everyone else answers on how to format a date as string.
I agree. Actually I wanted to write an answer similar to this one and then a small window popped up asking me whether I've read through all the answers. Since I've read only the top answers, I decided to check whether there are any correct answers and this one was the first correct answer.
This sets hours using UTC, which might not work for all use cases.
I also agree. Answers the question perfectly. Thank you.
121

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
Dan Atkinson
11.8k14 gold badges89 silver badges116 bronze badges
answered Feb 15, 2012 at 8:48

Comments

69

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/

answered Dec 12, 2012 at 1:03

3 Comments

Supports localization like a charm.
These days we use date-fns - it treats dates as Immutable (Moment mutates dates), is faster and is modular (just import what you need).
Six years after posting this momentjs has put on quite a bit of weight. You may want to check out github.com/iamkun/dayjs instead - I've had it described to me as "momentjs on a diet". Same simple API.
69
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.

tagurit
5786 silver badges16 bronze badges
answered Jul 9, 2014 at 7:01

3 Comments

Nice, works on Chrome. Unfortunately doesn't work on PhantomJS as of 22/4/2016
cool solution. should be on the top. new Date().toLocaleDateString("de-de") does the trick for me.
Use new Date().toLocaleDateString("en-US", { "year": "numeric", "day": "numeric", "month": "long", }); if you need the month name instead of number.
63

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>

Michael
5251 gold badge11 silver badges30 bronze badges
answered Aug 16, 2014 at 11:56

4 Comments

Moment is overkill for just getting the current date.
Or moment().format("L") to respect the current locale.
@DanDascalescu Actually, the Javascript base specification for DateTime is that bad.
If you already have momentjs imported in your project then this is the cleanest simplest answer.
58

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"

Michael
5251 gold badge11 silver badges30 bronze badges
answered Jun 28, 2013 at 22:32

2 Comments

I needed a time in 00:00:00 and didn't want to rebuild it manually; step 2 gets me there perfectly. Kudos!
You can save some bytes by doing this: Date().split(' ').splice(1,3).join(' ')
53

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.

answered Feb 8, 2021 at 6:12

3 Comments

Thank you! I knew date had to have a string method, I don't know why everyone is parsing out days and months and years and concatenating.. Even if you wanted dashes: Date().toISOString().split('T')[0].replaceAll('/','-')
Yeah, maybe they had something else in mind.
Thank you, I was looking for what's needed to set value in an input date, and this is it – it should be the most common use case!
52

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

answered Nov 3, 2013 at 18:03

Comments

51

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale:

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

answered Jul 18, 2016 at 17:15

Comments

34

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日

answered Mar 10, 2018 at 14:48

1 Comment

Since the length is always fixed, we can use substring as well. new Date().toISOString().substring(0, 10); Might be a bit faster as well.
25

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

answered Jun 26, 2012 at 13:00

1 Comment

if you are using jquery ui with a datepicker, you can use $.datepicker.formatDate('yy/mm/dd', new Date())
22

Using the JavaScript built-in Date.prototype.toLocaleDateString() (more options are in the MDN documentation):

const options = {
 month: '2-digit',
 day: '2-digit',
 year: 'numeric',
};
console.log(new Date().toLocaleDateString('en-US', options)); // mm/dd/yyyy

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'
Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
answered Oct 8, 2020 at 19:34

Comments

21

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

answered May 15, 2015 at 14:40

1 Comment

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

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.

answered Aug 11, 2015 at 6:08

Comments

17

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

answered May 18, 2018 at 7:27

Comments

16

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

answered Dec 1, 2017 at 21:43

2 Comments

I was looking for a very simple seed function that changes regularly. This answer is a real treat.
don't use this it gets the previous date at 7am
15
new Date().toDateString();

Result:

"Wed Feb 03 2016"

answered Feb 3, 2016 at 12:08

Comments

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

would work too

answered Oct 1, 2015 at 16:19

Comments

13

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

answered Jun 30, 2015 at 8:10

Comments

13

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)

answered Mar 3, 2020 at 13:00

2 Comments

Question is for javascript.
@JaydeepShil - this is javascript solution - if you don't believe run above snippet or copy-paste it to chrome console
12

This is good to get a formatted date

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

Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
answered Jul 11, 2019 at 8:00

Comments

11

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.

answered Jan 20, 2017 at 12:35

Comments

10

A straightforward 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
Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
answered Feb 18, 2020 at 16:46

Comments

9

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

answered Aug 11, 2015 at 6:31

Comments

8

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>
ROMANIA_engineer
57k30 gold badges211 silver badges207 bronze badges
answered Feb 8, 2013 at 12:07

Comments

8

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月07日T07: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月07日T07:00:00.000Z

Clean and simple.

answered Oct 1, 2015 at 15:25

5 Comments

Where is the explanation of how this answer works and why you feel it is good advice?
I don't understand from where came this sudden attack? I don't see that you asked that question to other answers? May I know why I have been awarded this way?
I don't understand why you feel this is an attack. Yes, I did blow the whistle on (several) other code-only answers. You have the ability to edit your post. Please improve it with the intention to educate/empower thousands of future researchers.
It is hard not to get the impression of an attack, after rough and high-hat imperative sentence. I will gladly improve my answer, but please next time don't assume that you have right to order people around. I really appreciate your care and your time to make Stackoverflow a better place, but believe me that nobody will want to cooperate with you if you will be treating people from high. Like sentence "Could you provide the explanation of how this answer works and why you feel it is good advice?" sound so much better in my eyes then "Where is...". Do you understand what I'm talking about?
I could answer the same: is this your way of self-appreciation? :) But I'm not going to continue this conversation because I see that it does not lead to anything.
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.