0

In my LWC I have a Datatable with a column for "Date From" - below is the column configuration

{
    label: 'Date From',
    fieldName: 'werDateFrom',
    type: 'date',
    sortable: true,
    typeAttributes: {
        day: "2-digit",
        month: "2-digit",
        year: "numeric"
    }
},

In the Datable the Date is formatting as desired - MM/DD/YY In another part of the LWC I am displaying the "From Date" value of the selected row.

event.detail.selectedRows[0].Date_From__c

However the format of this is YYYY-MM-DD. How can I adjust this to use the MM/DD/YY format.

1 Answer 1

0

You could use Formatted Date Time component to display the date in the desired format, which is the same component used internally by datatable.
Indeed the attributes to format the date as MM/DD/YY are the same: year="numeric" + month="2-digit" + day="2-digit".
I.E.

<lightning-formatted-date-time
    value="2022-12-02"
    year="numeric"
    month="2-digit"
    day="2-digit">
</lightning-formatted-date-time>

Of course you should use your field as value.


Edit

Format a date in Javascript

If you have a Date object you could leverage toLocaleDateString(locale, options). The first parameter is a string with the IETF language tag, i.e. en-US, while the second one is an object with several attributes to specify the date formatting style and the ones you need are the same used in Formatted Date Time component.
To build a Date object, if you don't have one, you could use Date.UTC(year, monthIndex, day). Keep in mind that monthIndex is an integer between 0 (January) and 11 (December).

const myDate = new Date(Date.UTC(2022, 11, 02)); 
const options = {  year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(myDate.toLocaleDateString('en-GB', options)); // "02/12/2022"
console.log(myDate.toLocaleDateString('en-US', options)); // "12/02/2022"
2
  • Thanks for the quick response. That is working perfectly in the HTML. I would like to build a string with multiple dates and other fields. Is there a way to format the date in the javascript ? Commented Dec 2, 2022 at 13:45
  • 1
    @JeffCallahan I updated the answer
    – RubenDG
    Commented Dec 2, 2022 at 14:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .