[javascript] How do I get the current date in JavaScript?

How do I get the current date in JavaScript?

This question is related to javascript date date-formatting

The answer is


This does a lot;

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

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


Pretty Print The Date Like This.

June 1st, 2015 11:36:48 AM

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


The shortest possible.

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

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

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

_x000D_
_x000D_
let today = new Date().toLocaleDateString()_x000D_
_x000D_
console.log(today)
_x000D_
_x000D_
_x000D_

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


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


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

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


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


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

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale:

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


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


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


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

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

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

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

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

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


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/


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


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

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.


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

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

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

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


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

Also, you can call method toLocaleDateString with two parameters:

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

Article on MSDN. More about this method on MDN.


If your looking to format into a string.

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

output "time 11:30:53 AM"


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.

_x000D_
_x000D_
var objToday = new Date(),_x000D_
 weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),_x000D_
 dayOfWeek = weekday[objToday.getDay()],_x000D_
 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" }(),_x000D_
 dayOfMonth = today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,_x000D_
 months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),_x000D_
 curMonth = months[objToday.getMonth()],_x000D_
 curYear = objToday.getFullYear(),_x000D_
 curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),_x000D_
 curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),_x000D_
 curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),_x000D_
 curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";_x000D_
var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;_x000D_
_x000D_
document.getElementsByTagName('h1')[0].textContent = today;
_x000D_
<h1></h1>
_x000D_
_x000D_
_x000D_

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.



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/


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


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

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


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

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"


Using JS built in Date.prototype.toLocaleDateString() From MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

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

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


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


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

If you want other formats then best to use momentjs.


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.

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


So many complicated answers...

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

Enjoy!


new Date().toDateString();

Result:

"Wed Feb 03 2016"


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.


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>

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

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


Try this:

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

The result will be like

15/2/2012

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

Date();

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


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

This works every time:

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


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


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

Just trying to help...

enter image description here


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.


This is good to get formatted date

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


My solution uses string literal Find out more...

_x000D_
_x000D_
// Declare Date as d_x000D_
var d = new Date()_x000D_
_x000D_
// Inline formatting of Date_x000D_
const exampleOne = `${d.getDay()}-${d.getMonth() + 1}-${d.getFullYear()}`_x000D_
// January is 0 so +1 is required_x000D_
_x000D_
// With Breaklines and Operators_x000D_
const exampleTwo = `+++++++++++_x000D_
With Break Lines and Arithmetic Operators Example_x000D_
Year on newline: ${d.getFullYear()}_x000D_
Year minus(-) 30 years: ${d.getFullYear() - 30}_x000D_
You get the idea..._x000D_
+++++++++++`_x000D_
_x000D_
console.log('=============')_x000D_
console.log(exampleOne)_x000D_
console.log('=============')_x000D_
_x000D_
console.log(exampleTwo)
_x000D_
_x000D_
_x000D_


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

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.


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;

} ());

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

would work too


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

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


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.


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

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

Try

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

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

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)


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;

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to date-formatting

How to insert date values into table How do I format a date as ISO 8601 in moment.js? Java Convert GMT/UTC to Local time doesn't work as expected Compare two date formats in javascript/jquery How to ISO 8601 format a Date with Timezone Offset in JavaScript? What are the "standard unambiguous date" formats for string-to-date conversion in R? How to convert date in to yyyy-MM-dd Format? Convert timestamp to date in MySQL query Date formatting in WPF datagrid Return date as ddmmyyyy in SQL Server