Issue
I'm using the following code to get a DateTime
value from the server in my ASP.NET Core Razor Pages application and set an <input />
element to that value.
$.ajax({
type: 'GET',
url: '?handler=InitProductTransfer',
contentType: 'application/json',
dataType: 'json',
data: { 'sourceId': sourceId, 'sourceType': sourceType },
})
.done(function (response) {
// Set timestamp
var $timeStamp = $modal.find('#TimeStamp');
$timeStamp.val(response.timeStamp); // <====== ERROR HERE!
}
.fail(function (response) {
alert(response.responseText);
});
The problem is that the date/time is not in the correct format.
The format of response.timeStamp
is 2023-10-31T15:23:55.0038809
.
Does JavaScript have a function to format the date for a date/time <input />
element? Or is it necessary to manually format the date to a string?
Solution
With vanilla JavaScript you can create a Date
object and pass it to the input using the valueAsDate
property:
let timeStamp = "2023-10-31T15:23:55.0038809";
document.getElementById("dateInput").valueAsDate = new Date(timeStamp);
<input id="dateInput" type="date" />
If your element has type="datetime-local
, you can use the following:
document.getElementById("dateInput").value = new Date(timeStamp).toISOString().slice(0, -1);
Answered By - Dimitris Maragkos
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.