In JavaScript, when you want to get the current date and time or store a given date and time in an object, you create a Date
object using the Date()
constructor.
// Get current date and time
var now = new Date();
console.log(now)
// Mon Feb 06 2023 10:32:32 GMT+0100 (Central European Standard Time)
By default, when you reference a Date object, you get:
- The three-letter acronym of the day of the week
- The three-letter acronym of the month
- A two-digit representation (DD) of the day, with a leading zero
- A four-digit representation (YYYY) of the year
- The time (HH:MM:SS) and time zone
What if you want the date formatted differently? And how can you get the date without the time in JavaScript?
Well, that’s what I’ll show you how to do in this blog post. As it turns out, there’s a method in JavaScript that lets you format dates however you want. And once you’ve mastered it, you will be able to format dates without adding bloat and weight to your code.
M/D/YYYY
To get the date in United States date format, or M/D/YYYY without leading zeros, use the toLocaleDateString()
method with the “en-US” locale on your date object:
// Get date in M/D/YYYY (en-US) format, without leading zeros
var now = new Date();
now.toLocaleDateString('en-US')
// 2/6/2023
MM/DD/YYYY
The toLocaleDateString()
method accepts options parameters that let you tweak its outputs so that you can get the date in the exact format you want.
To get the date in United States format with leading zeros, or MM/DD/YYYY, pass on the following values for the options parameter of the toLocaleString()
method:
// Get date in MM/DD/YYYY (en-US) format, with leading zeros
var now = new Date();
now.toLocaleDateString('en-US', { day: "2-digit", month: "2-digit", year: "numeric" })
// 02/06/2023
Month, D, YYYY
To get the date in United States format with the full name of the month followed by “D, YYYY” without leading zeros, use the following values for the options parameter of the toLocaleString()
method:
// Get date in Month, DD, YYYY (en-US) format, without leading zeros
var now = new Date();
now.toLocaleDateString('en-US', { day: "numeric", month: "long", year: "numeric" })
// February 6, 2023
DD/MM/YYYY
To get the date in Great Britain date format, or DD/MM/YYYY with leading zeros, use the toLocaleString()
method with the “en-GB” locale on your date object:
// Get date in DD/MM/YYYY (en-GB) format, with leading zeros
var now = new Date();
now.toLocaleDateString('en-GB')
// 06/02/2023
In Summary
To store date and time in JavaScript, create a Date
object with the Date()
constructor and store it in a constant or variable. And to get the date from this object in the format you need, use the toLocaleDateString()
method.
This beauty of this approach is that you preserve the date and time data in the Date
object while showing the date itself, without the time, in whatever locale you need to.