我有一个日期时间变量“whenDateTime”,它是从我的数据库中读取的格式(YYYY-MM-DDTHH:mm:ss.000)。 我想用这个日期时间设置一个datetimepicker,然后能够操作它,当然把它写回我的数据库。
由于某种原因,datetimepicker不会触发。我哪里出错?
这是我的观点模型:
function ViewModel() {
var self = this;
self.whenDateTime = ko.observable("2016-04-09T19:24:48.000");
self.viewWhenDateTime = ko.computed({
read: function () {
var mydate = self.whenDateTime();
if (!mydate) {
return null;
} else {
return moment(mydate).format("DD.MM.YYYY HH:mm");
}
},
write: function (newVal) {
var reversed = moment(newVal).format();
self.whenDateTime(reversed);
}
});
}
bindingHandlers是这样的:
ko.bindingHandlers.dateTimePicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().dateTimePickerOptions || {};
$(element).datetimepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "dp.change", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
if (event.date != null && !(event.date instanceof Date)) {
value(event.date.toDate());
} else {
value(event.date);
}
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
var picker = $(element).data("DateTimePicker");
if (picker) {
picker.destroy();
}
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var picker = $(element).data("DateTimePicker");
//when the view model is updated, update the widget
if (picker) {
var koDate = ko.utils.unwrapObservable(valueAccessor());
//in case return from server datetime i am get in this form for example /Date(93989393)/ then fomat this
koDate = (typeof (koDate) !== 'object') ? new Date(parseFloat(koDate.replace(/[^0-9]/g, ''))) : koDate;
picker.date(koDate);
}
}
};
答案 0 :(得分:1)
当我操作小提琴(https://jsfiddle.net/9aLvd3uw/237/)时,它实际显示09/04/2016 7:24 PM
2016-04-09T19:24:48.000
,当我更改输入日期时,它会正确更改。我无法复制你提到的内容。
注意每当moment.js想要解析日期时,如果该日期未定义或以错误的格式提供,则会显示当前日期。