We can use JavaScript to get today’s date by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. We will go over some of our favorites.
The JavaScript toLocaleString method will take a date object and return the date as a string using the local settings from your computer.
var currDate = new Date();
var localDate = currDate.toLocaleString();
The date is returned in a much friendlier format for the user than what the Date() method returns. The outputs of currDate and localDate from above are displayed as follows:
localDate: 1/28/2022, 9:35:02 PM
As you can see, the day of the week is not included in the default toLocaleString output. But there are tons of options you can include as parameters to the toLocaleString method which can be found here. The following setup is one we like best:
var currDate = new Date();
var localDate2 = currDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'short'});
Which would display the date and time as follows:
Another option is to leave the time off of the date, and just display the day, month, and year.
var currDate = new Date();
var localDate2 = currDate.toLocaleString('en-US', { dateStyle: 'full'});
console.log(localDate2);
#Output
Tuesday, August 30, 2022
This is the preferred date format we will choose to use going forward.
Displaying the Current Date and Time using the JavaScript toLocaleString Method
Below we will provide code to get the current date in JavaScript, and let the user see it in a friendly format when they click a button.
Get Date
Today's Date is:
We will simply get the Date with with the Date() method, and use the toLocaleString() method and some parameter options to display the date and time nicely. Here is the simple JavaScript code:
function genNewDate(){
var currDate = new Date();
var localDate = currDate.toLocaleString('en-US', { dateStyle: 'full'});
document.getElementById("theDate").innerHTML = localDate;
}
The final code and output for this example is below:
Code Output:
Today’s Date is:
Full Code:
Get Date
Today's Date is:
<script>
function genNewDate(){
var currDate = new Date();
var localDate = currDate.toLocaleString('en-US', { dateStyle: 'full'});
document.getElementById("theDate").innerHTML = localDate;
}
</script>
Hopefully this article has been useful in helping you understand how to use JavaScript to get today’s date.