Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Format Date in JavaScript

JavaScript - How to Format Date in JavaScript

Most developers, at some point in their career, will need to handle the very common task of formatting a time or date in JavaScript. While there are endless reasons to display (or manipulate) current, past, and future times and dates, the problem faced by many JavaScript developers is that the tools and methods to do so can seem equally endless.

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.

Moment.js

While JavaScript’s native date and time manipulation functions can cover all of our formatting needs, they can still be challenging to use. In many cases, external libraries can make our work easier, with more humane interfaces that are easier to integrate and work with.

Moment.js is a great example. This very popular and easy-to-use library contains thousands of functions all aimed at date, time, and time zone formatting.

Here are a few sample lines using Moment.js to manage time formatting:

let now = new Date();
 
var dateString = moment(now).format('YYYY-MM-DD');
console.log(dateString) // Output: 2020-07-21
 
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:MM:SS');
console.log(dateStringWithTime) // Output: 2020-07-21 07:24:06

As you can see above, Moment.js can accomplish many of the things possible with the JavaScript date library, and often with less verbosity in the underlying code. Here are a few examples of things that can be easily achieved with Moment.js that would be challenging using the built-in libraries:

let basicFormat = moment();
console.log(basicFormat)  //Output: { Object }
 
let basicFormatUTC = moment.utc().format();
console.log(basicFormatUTC)  // Output: 2020-07-21T07:24:06Z
 
let dayFormat = moment().format('dddd');
console.log(dayFormat);  // Output: Tuesday
 
let yearsAgo = moment("20111031", "YYYYMMDD").fromNow();
console.log(yearsAgo);  // Output: 9 years ago
 
let currentLocalTime = moment().format('LTS');
console.log(currentLocalTime);  // Output: 7:24:06 AM
 
let timeInLA = basicFormat.tz('America/Los_Angeles').format('ha z');
console.log(timeInLA);  // Output: 12am PDT

While you can implement all of the above functions using JavaScript’s built-in time and date functions, Moment.js lets us simplify these tasks, reducing the changes needed to a single line of code in many cases. This ease of use takes away the hassle of date and time formatting, making working with time objects a real breeze.

To dive deeper into the power and capabilities of Moment.js, check out this page.

 

Related Articles:

JavaScript – How to Use Date.parse

JavaScript – How to Use JSON.stringify

JavaScript – How to Change The Page URL

Get AI Code Completions for Your IDE