2975

How do I get the current date in JavaScript?

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
Suresh
  • 38,717
  • 16
  • 62
  • 66
  • 17
    See the [documentation for the Date object](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date). It has examples. – Quentin Oct 07 '09 at 11:40
  • 5
    this would help you http://www.tizag.com/javascriptT/javascriptdate.php –  Dec 01 '11 at 04:34
  • 470
    `var currentTime = new Date();` – Hendrik Oct 07 '09 at 11:39
  • 37
    `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). – Steve Bennett Apr 12 '15 at 01:01
  • 16
    use momentJs, this lib is gold for developers. – RBoschini Dec 22 '15 at 17:30
  • 5
    @SteveBennett Actually, it returns the current date _and_ time. JavaScript doesn't have separate objects to represent a date-only value or a time-only value. It has only `Date`, which incorporates both. So, even if the question isn't exactly clear, the expected answer is to obtain the current system date and time, which is exactly what `new Date()` returns, so +1 to @Hendrik for the most concise answer. – Suncat2000 Dec 22 '15 at 18:14
  • See this post : http://stackoverflow.com/a/30245911/1579667 – Benj Dec 21 '16 at 13:23
  • Surprised to not see a comment about the great date-fns library. Modular (just import what you need), treats Dates as immutable, work with native Date objects, faster than Moment. – Freewalker Dec 02 '17 at 15:11
  • 3
    **Your question is very broad!** Do you want a string (easy) or a date object (traps)? Do you want the current date where you are, or in London, or somewhere else? ***[BEWARE THE TIMEZONE](https://stackoverflow.com/a/38050824/1585345)*** – bbsimonbb Sep 19 '18 at 09:14
  • 2
    new Date() is still valid and best answer but after that the need of particular format comes up and I would suggest to use toLocaleDateString with new Date e.g. ```new Date().toLocaleDateString('en-GB', {year: "numeric", month: "2-digit", day: "2-digit"})```which in the end give you formatted current date in this format 08/06/2021. – Przemek Nowicki Jun 08 '21 at 14:23
  • [Luxon](https://moment.github.io/luxon/) is a modern library from one of the momentjs developers. Really nice interface and APIs! – Lars Flieger May 25 '22 at 13:39

61 Answers61

3407

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.

mohshbool
  • 41
  • 2
  • 9
Samuel Meddows
  • 36,162
  • 12
  • 38
  • 36
  • 7
    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 Jul 15 '13 at 15:15
  • 23
    @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` – zfm Jul 19 '13 at 06:20
  • 11
    @MounaCheikhna - How could we be in the year 999? – nnnnnn Apr 23 '14 at 22:36
  • 40
    Swap around the month and date if you're not in north America. – Mark Micallef Jun 11 '14 at 04:11
  • 1
    @MounaCheikhna why are you adding 1900? If we were in the year 999, this would make it 2899 (999 + 1900) – Niko Bellic Sep 18 '14 at 16:31
  • I wrapped it in a function for my own use, providing it here > http://jsfiddle.net/johndkane/cmzppwps/ – John K May 06 '15 at 21:55
  • 18
    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()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) – Adam Brown Feb 16 '16 at 16:53
  • Today I found a pretty neat trick. `('0' + today.getDate()).slice(-2)` This returns the current date always as 2 digits. – cee Apr 11 '16 at 20:54
  • 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 :) – delphirules Mar 09 '17 at 19:16
  • 2
    date.toLocaleDateString('en-GB') – Sakshi Nagpal Jun 24 '18 at 17:44
  • 4
    after the edit from March 2019, this answer is using ES2017 features (`padStart`) that will NOT work in Internet Explorer (any version) – Aprillion Aug 05 '19 at 14:10
  • @Aprillion just use polyfills such as corejs – DSLuminary Feb 10 '20 at 22:41
  • Why can't we just use the simple getDate(), getMonth() methods. What is reason we are putting padStart and + 1 with that. I tried this and it is working fine. `var today = new Date(); document.getElementById("demo1").innerHTML = day =today.getDate(); document.getElementById("demo2").innerHTML = month=today.getMonth(); document.getElementById("demo3").innerHTML = year=today.getFullYear(); document.getElementById("demo").innerHTML = year.toString()+month.toString()+day.toString();` – Rashid Apr 23 '20 at 12:06
535

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 S.
  • 1,383
  • 14
  • 25
Varun Natraaj
  • 7,402
  • 2
  • 18
  • 19
450

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.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
277

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
  • 227
  • 1
  • 9
  • 22
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • 15
    @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. – SpYk3HH Feb 06 '14 at 15:32
  • 16
    moment.js is now the thing you would use these days – Christian Stewart Sep 17 '14 at 22:26
  • 1
    Above, there is a typo (that took me awhile to spot), it uses a variable "today" in the line: " dayOfMonth = today + " – user1435707 Oct 18 '17 at 14:36
  • "today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder" - JS is stupid language. – Alex S Jan 09 '18 at 14:56
  • Its just 39 past noon and it prints 12:39 am. – phi lo czar Apr 26 '22 at 09:40
220

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

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

document.write(today);
Michael
  • 495
  • 1
  • 11
  • 29
Marshal
  • 4,452
  • 1
  • 23
  • 15
  • 50
    This seems to be the only answer that actually answers the question. Everyone else answers on how to format a date as string. – Inrego Sep 30 '15 at 12:39
  • 1
    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. – Lajos Arpad Feb 10 '19 at 11:18
  • This sets hours using UTC, which might not work for all use cases. – McKay Feb 15 '20 at 00:08
  • 2
    I also agree. Answers the question perfectly. Thank you. – JoBaxter Aug 02 '21 at 14:42
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,391
  • 14
  • 81
  • 114
Jimmy M
  • 1,627
  • 3
  • 14
  • 18
68

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/

benjamin.keen
  • 1,936
  • 1
  • 20
  • 29
  • 7
    Supports localization like a charm. – Risadinha Aug 27 '13 at 08:33
  • These days we use date-fns - it treats dates as Immutable (Moment mutates dates), is faster and is modular (just import what you need). – Freewalker Jun 06 '17 at 21:21
  • 2
    Six years after posting this momentjs has put on quite a bit of weight. You may want to check out https://github.com/iamkun/dayjs instead - I've had it described to me as "momentjs on a diet". Same simple API. – benjamin.keen Nov 21 '18 at 00:36
65
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
  • 494
  • 5
  • 13
Dunaevsky Maxim
  • 3,062
  • 4
  • 21
  • 26
  • Nice, works on Chrome. Unfortunately doesn't work on PhantomJS as of 22/4/2016 – chris Apr 22 '16 at 16:04
  • 1
    cool solution. should be on the top. `new Date().toLocaleDateString("de-de")` does the trick for me. – user3772108 May 06 '19 at 13:40
  • Use `new Date().toLocaleDateString("en-US", { "year": "numeric", "day": "numeric", "month": "long", });` if you need the month name instead of number. – mikasa Nov 21 '22 at 20:40
64

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
  • 495
  • 1
  • 11
  • 29
Morad
  • 2,761
  • 21
  • 29
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
  • 495
  • 1
  • 11
  • 29
Rishabh Marya
  • 717
  • 6
  • 4
  • 2
    I needed a time in 00:00:00 and didn't want to rebuild it manually; step 2 gets me there perfectly. Kudos! – panhandel Sep 18 '13 at 06:16
  • 4
    You can save some bytes by doing this: `Date().split(' ').splice(1,3).join(' ')` – hyde Mar 02 '15 at 21:42
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);
roshan
  • 2,410
  • 2
  • 25
  • 37
51

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.

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
50

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale:

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

Oded Breiner
  • 28,523
  • 10
  • 105
  • 71
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

Aung Htet
  • 711
  • 8
  • 6
  • 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. – Mika Karjunen Aug 06 '19 at 11:29
25

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

eomeroff
  • 9,599
  • 30
  • 97
  • 138
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
  • 30,738
  • 21
  • 105
  • 131
Constantin
  • 3,655
  • 1
  • 14
  • 23
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

Jose Rojas
  • 3,490
  • 3
  • 26
  • 40
20

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.

Community
  • 1
  • 1
user1338062
  • 11,939
  • 3
  • 73
  • 67
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',' '));
jafarbtech
  • 6,842
  • 1
  • 36
  • 55
16

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

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114
15
new Date().toDateString();

Result:

"Wed Feb 03 2016"

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

would work too

Toucouleur
  • 1,194
  • 1
  • 10
  • 30
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('/') );
Phil Ricketts
  • 8,236
  • 3
  • 28
  • 31
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)

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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.

Cam
  • 365
  • 3
  • 10
11

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
  • 30,738
  • 21
  • 105
  • 131
Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
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
  • 30,738
  • 21
  • 105
  • 131
Caiuby Freitas
  • 279
  • 2
  • 7
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

Akhil
  • 443
  • 1
  • 9
  • 29
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
  • 54,432
  • 29
  • 203
  • 199
Roger
  • 1,693
  • 1
  • 18
  • 34
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-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.

marverix
  • 7,184
  • 6
  • 38
  • 50
  • Where is the explanation of how this answer works and why you feel it is good advice? – mickmackusa May 04 '20 at 11:27
  • 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? – marverix May 05 '20 at 13:06
  • 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. – mickmackusa May 05 '20 at 21:46
  • 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? – marverix May 07 '20 at 07:04
  • 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. – marverix May 07 '20 at 07:12
8
// Try this simple way

const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);
Force Bolt
  • 1,117
  • 9
  • 9
  • Answer's are great. But for best practices, please provide an explanation. You only posting code makes the OP and future commers copy and paste your answer without understanding the logic behind the answer. Please provide an answer with some explanation. Thank You! – Buddy Bob May 12 '21 at 02:34
7

If you are using jQuery. Try this one liner :

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

Here is the convention for formatting the date

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

Here is the reference for jQuery datepicker

Souvik
  • 813
  • 10
  • 7
7

This does a lot:

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

Where today.getFullYear() gets the current year.

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

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

All of this is concatenated with '/'.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anil shrestha
  • 2,136
  • 2
  • 12
  • 26
6

If you’re looking to format into a string.

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

Output: "time 11:30:53 AM"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harry Bosh
  • 3,611
  • 2
  • 36
  • 34
  • Why the Date.now()? var x = new Date(Date.now()).toLocaleTimeString(); var y = new Date().toLocaleTimeString(); x === y – Jeff Lowery Apr 04 '19 at 18:24
5
var dateTimeToday = new Date();
var dateToday = new Date(
    dateTimeToday.getFullYear(), 
    (dateTimeToday.getMonth() + 1) /*Jan = 0! */, 
    dateTimeToday.getDate(), 
    0, 
    0, 
    0, 
    0);
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Jas
  • 516
  • 1
  • 6
  • 13
5

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

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

ISONecroMAn
  • 1,460
  • 2
  • 16
  • 23
  • 1
    It would return mistakes, like this `3/4/2018, `, better to use `new Date().toJSON().slice(0,10)`. – DevonDahon Mar 04 '18 at 09:16
  • 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)` – Paul Carlton Apr 03 '18 at 19:37
5

So many complicated answers...

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

Enjoy!

IonicMan
  • 743
  • 1
  • 12
  • 31
4

Pretty Print The Date Like This.

June 1st, 2015 11:36:48 AM

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

Andrew
  • 3,733
  • 1
  • 35
  • 36
4

This may help you

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

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

Jayant Patil
  • 1,537
  • 2
  • 11
  • 18
4

TL;DR

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

Reliable sources are:

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

Details

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

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

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

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

Another source mentioning this is: JavaScript date and time object

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

Some reliable sources that you can use are:

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

Community
  • 1
  • 1
Consta Gorgan
  • 549
  • 6
  • 22
4

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

(new Date()).toISOString().slice(0, 10).split("-").reverse().join("/")
SarjanWebDev
  • 523
  • 3
  • 11
3

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

var date = new Date();
var TimeStamp = date.toLocaleString();

function CurrentTime(){
  alert(TimeStamp);
}

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

Brock Davis
  • 159
  • 1
  • 5
  • 14
3

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

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

Here's the pad function:

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

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

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

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

The basics

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

var today = new Date();

Date.prototype.toLocaleDateString()

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

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

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

Going custom

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

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

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

day: 24
dayPadded: "24"
month: 1
monthPadded: "01"
monthName: "January"
year: 2016
John Slegers
  • 45,213
  • 22
  • 199
  • 169
2

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

Just trying to help...

enter image description here

Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
2

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jyotibisht
  • 80
  • 10
1
(function() { var d = new Date(); return new Date(d - d % 86400000); })()
Pranav Singh
  • 17,079
  • 30
  • 77
  • 104
Andrea
  • 884
  • 1
  • 10
  • 23
1

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

 var dt = new Date();  
       /// ANY DATE YOU WANT --  dt = new Date(""July 21, 1983 01:15:00"")

       dateObj = dt.getFormattedDate();

       alert( dateObj.isToday() );
       alert( dateObj.todayDay() );
       alert( dateObj.monthNameDayYear() );

(function () {

    fnDateProcessor = function () {
        var that = this;

        return {

            yyyymmdd: function (separator) {
                var fdate = this.formatDate(true, true) ,
                    separator = separator ? separator : "-";
                return fdate.year + separator + fdate.month + separator + fdate.day;
            },

            monthNameDayYear: function () {
                var fdate = this.formatDate(true, true);
                return fdate.monthName + " " + fdate.day + ", " + fdate.year;
            },

            ddmmyyyy: function (separator) {
                var fdate = this.formatDate(true, true) ,
                    separator = separator ? separator : "/";
                return fdate.day + separator + fdate.month + separator + fdate.year;
            },

            meridianTime: function () {
                var fdate = this.formatDate();
                return fdate.hour + ":" + fdate.minute + " " + fdate.meridian;
            },

            monthDay: function (separator) {

                var fdate = this.formatDate();
                separator = checkSeparator(separator);
                return fdate.monthName.substring(0, 3) + separator + fdate.day;

            },

            weekMonthDayYear: function () {
                var fdate = this.formatDate();
                //separator = checkSeparator(separator);

                return fdate.weekDay + " " + fdate.monthName.substring(0, 3) +
                    fdate.day + " ," + fdate.year;
            },

            timeZoneInclusive: function () {

                return new Date(that);
            },

            todayDay: function () { return new Date().getDate(); },
            todayMonth: function () { return new Date().getMonth() + 1; },
            dateDay: function () { return this.formatDate().day; },
            dateMonth: function () { return this.formatDate().month; },
            isToday: function () { return this.sameDate(new Date()); },
            isYesterday: function () {
                d = new Date(); d.setDate(d.getDate() - 1);
                return this.sameDate(d);
            },

            formatDate: function () {
                var zeroPaddedMnth = true, zeroPaddedDay = false,
                    zeroPaddedHr = false, zeroPaddedMin = true;
                // Possible to take Options arg that overide / merge to defaults

                var monthNames = [
                    "January", "February", "March",
                    "April", "May", "June", "July",
                    "August", "September", "October",
                    "November", "December"
                ];
                var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

                var day = getFormattedDay(that.getDate(), zeroPaddedDay);
                var monthIndex = that.getMonth();
                var month = getFormattedMonth(monthIndex + 1, zeroPaddedMnth);
                var year = that.getFullYear();
                var wkDay = that.getDay();
                var hour = getFormattedHour(that.getHours(), zeroPaddedHr);
                var minute = getFormattedMinute(that.getMinutes(), zeroPaddedMin);
                var meridian = getMeridian(that.getHours());

                return {
                    "day": day, "monthName": monthNames[monthIndex], "month": month,
                    "weekDay": weekDays[wkDay], "year": year, "hour": hour, "minute": minute,
                    "meridian": meridian
                };
            },

            compareDate: function (d2) {     /// validates if caller is less than argument                            
                d2 = _isString(d2) ? new Date(d2) : d2;

                return !this.sameDate(d2)
                    && typeof d2 != "number"
                    ? that < d2 : false;
            },

            sameDate: function (d) {
                return that.getFullYear() === d.getFullYear()
                    && that.getDate() === d.getDate()
                    && that.getMonth() === d.getMonth();
            },

            dateAfter: function (separator) {
                var fdate = this.formatDate();
                var separator = separator ? separator : "-";
                return fdate.year + separator + fdate.month + separator + (fdate.day + 1);
            }

        };

    };


    function _isString(obj) {
        var toString = Object.prototype.toString;
        return toString.call(obj) == '[object String]';
    }

    function checkSeparator(separator) {
        // NOT GENERIC ... NEEDS REVISION
        switch (separator) {
            case " ": sep = separator; break;
            case ",": sep = " ,"; break;
            default:
                sep = " "; break;
        }

        return sep;
    }

    function getFormattedHour(h, zeroPadded) {
        h = h % 12;
        h = h ? h : 12;    //  12 instead of 00
        return zeroPadded ? addZero(h) : h;
    }

    function getFormattedMinute(m, zeroPadded) {

        return zeroPadded ? addZero(m) : m;
    }

    function getFormattedDay(dd, zeroPadded) {

        return zeroPadded ? addZero(dd) : dd;
    }
    function getFormattedMonth(mm, zeroPadded) {

        return zeroPadded ? addZero(mm) : mm;
    }

    function getMeridian(hr) {

        return hr >= 12 ? 'PM' : 'AM';
    }

    function addZero(i) {
        if (i < 10) {
            i = "0" + i;
        }
        return i;
    }


    Date.prototype.getFormattedDate = fnDateProcessor;

} ());
Yergalem
  • 1,603
  • 18
  • 14
1

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

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

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

Print something like this in the console:

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alain.janinm
  • 19,951
  • 10
  • 65
  • 112
1

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

new Date();

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

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

For a full list of supported formats, see here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
agDev
  • 855
  • 10
  • 20
1

Try Date.js

Milliseconds

date.js.millisecond(); // 0.00

Seconds

date.js.second(); // 58

Minutes

date.js.minute(); // 31

Hours

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

Days

date.js.day(); // Monday

Weeks

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

Month

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

TLM (Three-Letter-Month)

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

Year

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

Season

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

Current Time in AM/PM

date.js.time(); // (Time / Zone: "PDT/EDT etc.") => 10:04 AM
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Parking Master
  • 551
  • 1
  • 4
  • 20
0

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

const locale = 'en-us';
const d = new Date(date);

const day = d.getDate();
const month = d.toLocaleString(locale, { month: 'long' });
const year = d.getFullYear();

const time = d.toLocaleString(locale, { hour12: false, hour: 'numeric', minute: 'numeric'});

return `${month} ${day}, ${year} @ ${time}`; // May 5, 2019 @ 23:41
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex Ivasyuv
  • 8,585
  • 17
  • 72
  • 90
0

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

Date();
Adrian Bartholomew
  • 2,506
  • 6
  • 29
  • 37
0

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

function getDate(){
  var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

  var today = new Date();
  var dd    = String(today.getDate()).padStart(2, '0');
  var mm    = months[today.getMonth()];
  var yyyy  = today.getFullYear();

  today = dd + "-" + mm + "-" + yyyy;
  return today;
}

getDate();
SpaceX
  • 2,814
  • 2
  • 42
  • 68
0

My way

let dateString = new Date().toLocaleString().split(',').find(() => true);
Mansour Alnasser
  • 4,446
  • 5
  • 40
  • 51
0

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

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

const currentTimezoneOffset = 8; // UTC+8:00 time zone, change it

Date.prototype.yyyymmdd = function() {
    return [
        this.getFullYear(),
        (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
        this.getDate().toString().padStart(2, '0')
    ].join('-');
};

function getTodayDateStr() {
  const d = new Date();
  // console.log(d);
  const d2 = new Date(d.getTime() + (d.getTimezoneOffset() + currentTimezoneOffset * 60) * 60 * 1000);
  // console.log(d2, d2.yyyymmdd());
  return d2.yyyymmdd();
}

console.log(getTodayDateStr());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
addlistener
  • 871
  • 1
  • 12
  • 20
0

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

// Get locale name
function getLang() {
  if (navigator.languages != undefined)
    return navigator.languages[0];
  return navigator.language;
}

// Get the current datetime with format yyyy-MM-ddThhmmss
const time = new Date().toLocaleString(getLang(), {
  hour12: false ,
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
}).replaceAll('/', '-').replaceAll(':', '').replaceAll(' ', 'T')

console.log("locale:", getLang())
console.log(time)

The result may looks like:

locale: zh-TW
2022-09-13T171642

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
allenyllee
  • 964
  • 1
  • 13
  • 16
-1

My solution uses string literals. Find out more...

// Declare Date as d
var d = new Date()

// Inline formatting of Date
const exampleOne = `${d.getDay()}-${d.getMonth() + 1}-${d.getFullYear()}`
// January is 0 so +1 is required

// With Breaklines and Operators
const exampleTwo = `+++++++++++
With Break Lines and Arithmetic Operators Example
Year on newline: ${d.getFullYear()}
Year minus(-) 30 years: ${d.getFullYear() - 30}
You get the idea...
+++++++++++`

console.log('=============')
console.log(exampleOne)
console.log('=============')

console.log(exampleTwo)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-1

Try this and you can adjust the date format accordingly:

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

var myDate = dd + '-' + mm + '-' + yyyy;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashish Pathak
  • 827
  • 8
  • 16
-2
Date.prototype.toLocalFullDateStringYYYYMMDDHHMMSS = function () {
if (this != null && this != undefined) {
    let str = this.getFullYear();
    str += "-" + round(this.getMonth() + 1);
    str += "-" + round(this.getDate());
    str += "T";
    str += round(this.getHours());
    str += ":" + round(this.getMinutes());
    str += ":" + round(this.getSeconds());
    return str;
} else {
    return this;
}

function round(n){
    if(n < 10){
        return "0" + n;
    }
    else return n;
}};
Yanir Calisar
  • 475
  • 4
  • 7
-6

Important note: do not use: var today = new Date();

But var dateToday = new Date();, for example, as var today does not indicate anything.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jorge
  • 89
  • 1
  • 4
  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32202583) – Mahyar Mottaghi Zadeh Jul 12 '22 at 18:41