Simran Verma

Simran Verma

  • Tech Writer
  • 2.5k
  • 109.5k

How to get date time conversion to local using lines of code

Jan 5 2024 8:47 AM

        document.addEventListener("DOMContentLoaded", function () {
            const utcDateElements = document.querySelectorAll('.date-utc');
            console.log("utcDateElements",utcDateElements);
            utcDateElements.forEach(function (element) {
                const utcDateString = element.getAttribute('data-utc-date');
                console.log("utcDateString",utcDateString);
                const dateParts = utcDateString.split('-'); 
                console.log("dateParts",dateParts);
                
                const utcDate = new Date(`${dateParts[1]}-${dateParts[0]}-${dateParts[2]}`);
                console.log("utcDate",utcDate);
                element.textContent = utcDate.toLocaleString(); 
            });
        });
that code workes fine on local but on staging give me invaild date text
I have to sent datetime from server that is in format 
05-01-2024 12:03:54


Answers (6)