我從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>
正如你所看到的,值2015-11-02
現在轉化爲UTC"2015-11-01T16:00:00.000Z"
時,我就可以用moment()
。這是我不希望的,因爲我想保留我從數據庫
了所以我的問題是:
我的臨時解決方案是post
的computed
變量。 (formattedDate
和它的工作原理)
請幫我理解錯誤發生的原因。任何幫助將非常感謝謝謝!
#1,我說的對,如果日期有'Z'在最後表示爲UTC基於ISO-8601格式? #2我嘗試使用'toDate',但結束髮布日期的最小值,而不是我使用'toISOString'。你怎麼看? –
如果使用'toISOString',則日期在時區Z中表示。並且,除非您製作自定義綁定程序ASP。NET MVC簡化日期沒有考慮到時區。對於該時區東部的任何國家(西歐,葡萄牙和英國除外)將獲得之前的日期。您可以嘗試在發佈之前使用'.utcOffset'時刻來糾正此問題。但是如果你開始使用日期和時間部分,這會導致問題。 – JotaBe
是的。但我不需要時間部分,因爲我只需要存儲'日期'和日期。我輪到一個日曆日期。我從數據庫中檢索到的值與它在頁面上顯示的值相同。沒有轉換。我有什麼選擇?由於'toDate()'會給我最小日期值。 'toISOString'會嗎? –