Search code examples
javascripthtmldatedomformat

how to change the date formant that is being displayed?


so im getting a date and time from the user by using datetime-local input type when display the value on my page, it looks like this: 2023-05-31T15:09

how can i change the date format to look more... readable? like: "31-05-2023, 15:09" etc dosnt really matter if there is "-" or "/" between date numbers.

const Date = document.getElementById("date").value
console.log(Date)
<input id="date" type="datetime-local" />


Solution

  • The first thing I would do is change the variable name. "Date" is a built-in JavaScript object. You can use toLocalString to format it the way you want. Here is my code please let me know if this is what you're looking for:

            const dateInput = document.getElementById("date");
            dateInput.addEventListener("change", () => {
    const selectedDate = new Date(dateInput.value);
    const formattedDate = selectedDate.toLocaleString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
    
    console.log(formattedDate);
    })
        <input id="date" type="datetime-local" />