JavaScript’s built-in time and date formatting methods can cover pretty much any situation involving time data that you can imagine. Yet, many developers choose to rely on third-party libraries to help them with this tedious and repetitive work. We’ll touch on those third-party solutions in a moment, but let’s get started with some basic JavaScript time formatting.
JavaScript’s Date() function object contains a long list of methods that can be used to manipulate the date outcome, as well as display time and date data as specific instances or ranges of time, dates, and time zones. Let’s look at the default Date() function below:
let date = new Date(); console.log(date); // Output: Tue Jul 21 2020 10:01:14 GMT+0100 (UK Daylight Time)
This example demonstrates the most common usage of the Date() function. If no other function is assigned, it prints the time and date in a localized format as seen above. We can modify the localized date string format by using the method toLocaleString(). Simply provide a language and a country (in standard locale code format, i.e. ‘en-US’) as arguments to the function, and the Date library will properly format the output to the desired locale:
console.log(date.toLocaleString('en-US')); // Output: 7/21/2020, 10:01:14 AM
In this example we used the toLocaleString() method to apply the “English-US” time format. The output matches the US English common time format: D/MM/YYYY HH:MM:SS AM/PM.
toLocaleString() allows us to customize specific sections of the provided result by modifying the associated parameters. Below is a list of the parameter names and types that are available when formatting time strings:
console.log(date.toLocaleString('en-US', { weekday: 'short', // long, short, narrow day: 'numeric', // numeric, 2-digit year: 'numeric', // numeric, 2-digit month: 'long', // numeric, 2-digit, long, short, narrow hour: 'numeric', // numeric, 2-digit minute: 'numeric', // numeric, 2-digit second: 'numeric', // numeric, 2-digit })); // Output: Tue, July 21, 2020, 10:01:14 AM
As you can see above, toLocaleString() receives a language code as the first parameter, and an optional object as the second parameter. This second parameter allows us to define the formatting for each part of the outcome result individually – the comments show the possible values for each potential key in the argument.
At this point, we’ve only scratched the surface of the things you can do with JavaScript’s Date() function. You can find more examples of how to use this powerful native library here.
Related Articles:
JavaScript – How to Use Date.parse