salesforcesalesforce-lightning

Convert date string from ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ ) to "MM-DD-YYYY HH:mm" in LWC


Tried :-

const dateStr = '2020-06-21T10:15:00Z',
[yyyy,mm,dd,hh,mi] = dateStr.split(/[/:-T]/)
console.log(${dd}-${mm}-${yyyy} ${hh}:${mi})

Split worked fine and I am getting 21-06-2020 10:15. How can we append AM/PM to this?


Solution

  • const dateStr = '2020-06-21T10:15:00Z';
    const [yyyy, mm, dd, hh, mi] = dateStr.split(/[-:T]/);
    
    // Convert hh to a 12-hour format and determine AM/PM
    const hour12 = (hh % 12) || 12; // Ensure 12-hour format, not 0 for midnight
    const ampm = hh < 12 ? 'AM' : 'PM';
    
    // Create the formatted date string
    const formattedDate = `${dd}-${mm}-${yyyy} ${hour12}:${mi} ${ampm}`;
    
    console.log(formattedDate);