Last updated: July 19, 2022.
A new Date object can be created as follows:
By default, the current date and time is returned.
Simple, right? But you’ve probably noticed that the returned object is rather lengthy and unlikely to be in the format we would wish users to see.
newoperator must precede the
Date()constructor. Otherwise a regular
stringis returned, not a
stringcannot be formatted in the same way using the operations described below.
Formatting a Date object using the toLocaleString() method
A more readable date and time format is easily created by applying the
.toLocaleString() method to a date object. The clever aspect of this method is that it returns the date and time in the accepted local format of the user accessing a website. So the date and time format is dynamic, changing from user to user.
To return the current date and time in the local format of a user, we can modify the initial
Date object and save it to a new variable:
If you are only interested in returning the current date in a user’s local format, use
To print the time only, use
Custom setting of date and time
A custom time can be entered manually in the following format
YYYY-MM-DDTHH:MM:SS. Following the same process, it can be entered in the local format of the user accessing it:
Forcing a date and time format
While adapting the date and time format to the user may be useful in some cases, in others it may be inappropriate. For example, your website or app may be for a country-specific audience. In this case, we can add a two-part language and country code in standard format to ensure that the format is always displayed in the same way, regardless of a user’s location:
To customise this to your language and location, check out this complete list of language and country codes provided by Oracle.