Monday, May 4, 2020

How to format Dates in lightning web components(lwc) using JavaScript

To format the javascript dates in custom formats we need to use the DateTimeFormat
The Intl.DateTimeFormat object is a constructor for objects that enable the language-sensitive date and time formatting.

Sample Code
let dt = new Date();
const dtf = new Intl.DateTimeFormat('en', {
    year: 'numeric',
    month: 'short',
    day: '2-digit'
})
const [{value: mo}, , {value: da}, , {value: ye}] = dtf.formatToParts(dt);

let formatedDate = `${da}-${mo}-${ye}`;
console.log('formatedDate ===> '+formatedDate);


Output

3 comments:

  1. Hi, see below a better solution, almost the same but shorter.

    let currentDate = new Date();

    let formatter = new Intl.DateTimeFormat('en', {
    year: "numeric" ,
    month: "numeric",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: "true"
    })

    let formattedDate = formatter.format(currentDate);

    return `${this.sectionTitle} (as of ${formattedDate})`;

    ReplyDelete