How do I get the current date in JavaScript?
How do I get the current date in JavaScript?
Use new Date() to generate a new Date object containing the current date and time.
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
document.write(today);
This will give you today's date in the format of mm/dd/yyyy.
Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.
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.
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'
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',' '));
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)
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);
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
// Try this simple way
const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);
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 '/'.
So many complicated answers...
Just use new Date() and if you need it as a string, simply use new Date().toISOString()
Enjoy!
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:
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().
If you’re looking to format into a string.
statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString();
Output: "time 11:30:53 AM"
In Australia, I prefer to get DD/MM/YYYY using this
(new Date()).toISOString().slice(0, 10).split("-").reverse().join("/")
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.
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/
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.
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();
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
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());
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.
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
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)
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;
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;
}};
Important note: do not use: var today = new Date();
But var dateToday = new Date();, for example, as var today does not indicate anything.