I have an HTML input type of "datetime-local" which I then store in a Datetime field in a MS SQL Server database. When I load the edit page I want to populate this HTML date field with the value from the database. When I console out the value of the date it is: "Tue May 16 2023 15:40:00 GMT+0200 (South Africa Standard Time)". Has anyone successfully converted a string like this to the accepted HTML date input format with Javascript?
Asked
Active
Viewed 75 times
1 Answers
0
Js has build in methods you can use that allow you to work with dates.
In the example below I:
- Convert the input string to a Date object using the
Date
method. - Extract the year from the Date object using the
getFullYear
method. - Extract the month from the Date object using the
getMonth
method.- Since the
getMonth
method returns a zero-based index of the month (January = 0, February = 1, etc.) we must do: result + 1. - Convert the month to a string.
- Use the
padStart
method to make sure the month string is 2 characters long. Example: if the extracted value = 1, then month = 01.
- Since the
- Extract the day from the Date object using the
getDay
method.- Convert the day to a string.
- Use the
padStart
method to make sure the day string is 2 characters long. Example: if the extracted value = 1, then day = 01.
- Format the date so it fits the HTML input format.
- Replace the HTML-elements value with the one we extracted.
const input = "Tue May 19 2024 15:40:00 GMT+0200 (South Africa Standard Time)";
const inputDate = new Date(input);
const year = inputDate.getFullYear();
const month = (inputDate.getMonth() + 1).toString().padStart(2, "0");
const day = inputDate.getDate().toString().padStart(2, "0");
const formattedDate = `${year}-${month}-${day}`;
const datePicker = document.getElementById('datePicker');
datePicker.value = formattedDate;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="date" id="datePicker" value="">
</body>
</html>

Smile4Blitz
- 59
- 3
-
Given how many times this has been asked before and the number of good answers, it really should be marked as a duplicate and left at that. ;-) – RobG May 17 '23 at 03:51