我从ASP.NET MVC /Date(1446393600000)/
获得了这个值,它在SQL数据库中的值是'2015-11-02'
,这是一个date
(仅限日期)并将其作为javascript对象操作,我已使用moment.js,因此在用作moment('/Date(1446393600000)/')
时,我得到了此结果"2015-11-01T16:00:00.000Z"
所以这段代码:
可以找到bindingHandler here
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().datepickerOptions || {},
$el = $(element);
//initialize datepicker with some optional options
$el.datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function() {
var observable = valueAccessor();
observable(moment($el.datepicker("getDate"))); // I added moment function here
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$el.datepicker("destroy");
});
}
/*,
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
$el = $(element),
current = $el.datepicker("getDate");
if (value - current !== 0) {
$el.datepicker("setDate", value);
}
}*/
};
var vm = {
sampleDate: ko.observable(moment('/Date(1446393600000)/')), // I added moment function here
originalValue: '/Date(1446393600000)/', // For reference only
FromSqlDb: '2015-11-02' // For reference only
};
vm.formattedDate = ko.pureComputed(function() {
return this.sampleDate() ?
this.sampleDate().format("ddd, DD MMM YYYY") :
'';
}, vm);
ko.applyBindings(vm);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="datepicker: sampleDate" /> <br />
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
&#13;
正如您所看到的,当我在其上使用2015-11-02
时,值"2015-11-01T16:00:00.000Z"
现已转换为 UTC moment()
。这是我不想要的,因为我想保留我从db获得的东西
所以我的问题是:
答案 0 :(得分:2)
日期是您选择的。使用时刻toDate
,您将得到一个具有预期值的js Date对象。你看到的是UTC表示,即转换到Z区(子午线0或格林威治子午线)的同一小时。
根据OP评论,使用.toISOString()
发布日期。在这种情况下,如果您所在的时区不是Z(格林威治子午线),则日期将参考上一个日期。例如,日期2015-04-20 GMT+1
将被格式化为2015-04-19T23:00:00.000Z
,服务器将剪切时间和时区信息,因此它将在所需日期前一天获得。
为避免2.中的问题,我们可以指示片刻解析日期,就像它是UTC日期一样,如下所示:moment.utc('datestring')
。例如,执行moment.utc('2015-03-11')
将创建日期2015-03-11T00:00:00.000Z
,因此ISO字符串的covnersion将提供所需的日期。在这种情况下,您必须更改以下代码行:
observable(moment($el.datepicker("getDate")))
到
observable(moment.utc($el.datepicker("getDate")))