Convert date from string to input type date format
P粉587780103
2023-09-05 21:31:29
<p>I have a "datetime-local" HTML input type which I then store in a datetime field in an 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:
"Tuesday, 16 May 2023 15:40:00 GMT 0200 (South African Standard Time)".
Has anyone successfully used Javascript to convert a string like this into an acceptable HTML date input format? </p>
Js has built-in methods that you can use to handle dates.
In the following example I:
Date
method to convert the input string into a Date object.getFullYear
method to extract the year from the Date object.getMonth
method to extract the month from the Date object.getMonth
method returns the zero-based month index (January = 0, February = 1, etc.), we must do the following: Result 1.padStart
method to ensure that the month string is 2 characters long. Example: If extracted value = 1, then month = 01.getDay
method to extract the date from the Date object.padStart
method to ensure that the date string is 2 characters long. Example: If extracted value = 1, then date = 01.