Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading