Suresh
Suresh

Reputation: 39541

How do I get the current date in JavaScript?

How do I get the current date in JavaScript?

Upvotes: 3041

Views: 4330261

Answers (30)

I.sh.
I.sh.

Reputation: 2108

The most flexible method that provides various formatting, is using Date.prototype.toLocaleDateString() (since ECMAScript 5.1):

For example:

const date = new Date();

// US English uses month-day-year order
console.log(date.toLocaleDateString("en-US"));
// "12/20/2012"

// British English uses day-month-year order
console.log(date.toLocaleDateString("en-GB"));
// "20/12/2012"

For more formats, check MDN Docs

In additions toLocaleDateString has an options argument that allow customization for those formats.

Upvotes: 0

mdcq
mdcq

Reputation: 2026

With the upcoming Temporal API (stage 3), you can use Temporal.PlainDateTime.

For example, for the current date and time in the ISO 8601 calendar you can use the plainDateTimeISO method on Temporal.Now

const datetime = Temporal.Now.plainDateTimeISO();
console.log(datetime.toString());

Similarly, for only the date you can use Temporal.PlainDate.

const date = Temporal.Now.plainDateISO();
console.log(date.toString());

And similarly for only the time you can use Temporal.PlainTime.

const time = Temporal.Now.plainTimeISO();
console.log(time.toString());

Upvotes: 0

Rahul
Rahul

Reputation: 41

This is only 2 lines.

let date = new Date().toLocaleDateString()
            .split("/")
            .map((d) => (d.length <= 1 ? "0" + d : d));

let newDate = `${date[1]}/${date[0]}/${date[2]}`;

console.log(newDate); // => dd/mm/yyyy

Upvotes: 0

allenyllee
allenyllee

Reputation: 1074

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.

Upvotes: 1

jyotibisht
jyotibisht

Reputation: 80

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.

Upvotes: 2

Harry Bosh
Harry Bosh

Reputation: 3790

If you’re looking to format into a string.

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

Output: "time 11:30:53 AM"

Upvotes: 8

alain.janinm
alain.janinm

Reputation: 20065

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/

Upvotes: 1

Alex Ivasyuv
Alex Ivasyuv

Reputation: 8844

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

Upvotes: 0

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3974

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

Upvotes: 12

anil shrestha
anil shrestha

Reputation: 3250

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

Upvotes: 8

Jerome Hurley
Jerome Hurley

Reputation: 33

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)

Upvotes: -1

agDev
agDev

Reputation: 865

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.

Upvotes: 1

Ashish Pathak
Ashish Pathak

Reputation: 824

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;

Upvotes: -1

Caiuby Freitas
Caiuby Freitas

Reputation: 289

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

Upvotes: 10

Constantin
Constantin

Reputation: 4011

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'

Upvotes: 22

Parking Master
Parking Master

Reputation: 626

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

Upvotes: 1

addlistener
addlistener

Reputation: 871

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

Upvotes: 0

Jorge
Jorge

Reputation: 99

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

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

Upvotes: -6

SarjanWebDev
SarjanWebDev

Reputation: 533

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

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

Upvotes: 5

Dunaevsky Maxim
Dunaevsky Maxim

Reputation: 3209

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.

Upvotes: 69

Oded Breiner
Oded Breiner

Reputation: 29749

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale:

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

Upvotes: 51

Shubham Chadokar
Shubham Chadokar

Reputation: 2773

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.

Upvotes: 53

Mansour Alnasser
Mansour Alnasser

Reputation: 5040

My way

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

Upvotes: 0

Force Bolt
Force Bolt

Reputation: 1221

// Try this simple way

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

Upvotes: 8

Akhil
Akhil

Reputation: 443

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

Upvotes: 9

IonicMan
IonicMan

Reputation: 902

So many complicated answers...

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

Enjoy!

Upvotes: 5

Yanir Calisar
Yanir Calisar

Reputation: 475

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

Upvotes: -2

marverix
marverix

Reputation: 7705

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.

Upvotes: 8

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92647

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)

Upvotes: 13

SpaceX
SpaceX

Reputation: 2890

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

Upvotes: 0

Related Questions