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 localDate2 = currDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'short'});
Which would display the date and time as follows:
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', timeStyle: 'short'});
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', timeStyle: 'short'});
document.getElementById("theDate").innerHTML = localDate;
}
</script>
Hopefully this article has been useful in helping you understand the JavaScript toLocaleString method.