0

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" />
cjs
  • 21
  • 6
  • Does this answer your question? [Is there any way to change input type="date" format?](https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format) – Konrad May 22 '23 at 18:50
  • What the browser shows in that input depends on the browser used and the language settings (I see `dd/mm/yyyy, --.--`). But the value is always something like 2023-05-31T15:09. An alternative could be to split it up into date and time in two different input elements. – chrwahl May 22 '23 at 19:27

1 Answers1

1

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" />
dram95
  • 444
  • 1
  • 7
  • 15