Thursday, 5 September 2013

Knockout.js rendering datetime 12/31/1969

Knockout.js rendering datetime 12/31/1969

Within a knockout VM I am trying to inject a date time into a property.
The function generates the correct date but when it is rendered out in the
UI I get a 12-31-1969 7pm date. This items is not being serialized and is
being generated on the fly. Can someone help me understand why this is
being generated and how to correct it. I have seen a number of articles on
where this appears in php code but nothing specific to knockout. There was
one article on SO that references the dateTimePicker but I did not
immediately see a similarity between the OP's issue or mine.
Within my js file
function returnDateFormat() {
var d = new Date();
date = d.getDate();
date = date < 10 ? "0" + date : date;
mon = d.getMonth() + 1;
mon = mon < 10 ? "0" + mon : mon;
year = d.getFullYear();
hours = d.getHours();
min = d.getMinutes();
sec = d.getSeconds();
return (mon + "/" + date + "/" + year + " " + hours + ":" + min + ":"
+ sec);
}
Where the function is referenced in my ajax call on success. Basically I
am trying to just update the VM to show the date when the event occured.
This gets loaded and is bound in the UI when the page initializes so I
know on the next load the correct value gets pulled from the DB and
populates. I just didn't want to return the entire dateset back from call
if I didn't have to.
$.ajax({
type: "POST",
url: "warehouse/" + command,
data: "{ productId:'" + product.ProductId() + "', newname: '" +
newname + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.Key == true) {
DisplaySuccess("Update Complete.", "The product has been
successfully updated.");
//update product name in VM
product.Name(newname);
product.DateLastModified(returnDateFormat());
}
else {
//Display error message if ajax msg fails
DisplayError("Error Renaming Product ", msg.Value);
}
}, error: function (err) {
DisplayError("Error Renaming Product", "The server returned an
error code. Code: " + err.status);
}
});
then in the cshtml file I have the date modifed element bound to a div
element
<div title="Product Last Modified" class="productDetailItem scalableText
productModified" data-bind="text: FormatDate(DateLastModified())"></div>
Update: On further investigation the original date is being passed in as a
Json serialized string this is what the cshtml function call to FormatDate
addresses. It parses and formats the Json string. I didn't realize this at
the time as I had not written this portion of the mapping.
The reason it was breaking was I passing in a formatted date time and not
a Json serialized string which the function expected. To correct this I
plan to generate client side a date time and then serialize it, pass it to
the function and this should correct the issue. I will post a working
solution soon. I would welcome other suggestions. -cheers

No comments:

Post a Comment