Simple date and time formatting in Javascript
Last updated: July 19, 2022.
Displaying the date and time is a common procedure in Javascript (e.g. to mark when an article or comment was posted).
The date and time can easily be generated as a Date object in Javascript by using the Date()
constructor.
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.
new
operator must precede the Date()
constructor. Otherwise a regular string
is returned, not a date
object. A string
cannot 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 .toLocaleDateString()
:
To print the time only, use .toLocaleTimeString()
:
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:
If only interested in the date, the time can simply be omitted and Javascript will select a time automatically:
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.