[英]get date selected by user without timezone
I have a few date fields in my form for which I am using JqueryUI
datepicker
for the user to select the date. 我在我的形式几个日期字段为此我使用JqueryUI
datepicker
供用户选择日期。 The date should be displayed in dd/mm/yy
format when the user selects a date. 用户选择日期时,日期应以dd/mm/yy
格式显示。 I am using KnockoutJS
to manage data binding on client side and using the following KO
binding handler for JqueryUI
datepicker
: 我用KnockoutJS
来管理数据在客户端的结合,并使用以下KO
装订处理器JqueryUI
datepicker
:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().datepickerOptions || { dateFormat: 'dd/mm/yy' };
$(element).datepicker(options);
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
Now when the user selects the date, it is displayed correctly in dd/mm/yy
format in the input
text
field and a javascript
Date
object along with timezone is getting captured in the KO
observable
. 现在,当用户选择日期时,它会以dd/mm/yy
格式正确显示在input
text
字段中,并且在KO
observable
捕获了javascript
Date
对象以及时区。 I am using ko.toJSON()
function to convert the entire complex javascript object
which contains various date fields to a JSON
string and deserializing it in the backend. 我正在使用ko.toJSON()
函数将包含各种日期字段的整个复杂javascript object
转换为JSON
字符串,并在后端对其进行反序列化。
The problem I am facing is when the javascript
Date
object is converted to JSON
string, it reduces one day from the user selected date which I am assuming is because of the local timezone and this is the default behaviour javascript date objects. 我面临的问题是将javascript
Date
对象转换为JSON
字符串时,它距用户选择的日期减少了一天,我认为这是由于本地时区,这是javascript日期对象的默认行为。 I have also tried the momentJs
library to get UTC
date from the selected date using the following code but this doesn't seem to work: 我还尝试了momentJs
库,使用以下代码从所选日期获取UTC
日期,但这似乎不起作用:
moment.utc(selectedDateObject).toDate()
What I want is to get whatever date the user selected in the form using the datepicker without any time zones, plain and simple. 我想要的是使用日期选择器获取用户在表单中选择的任何日期,而没有任何时区,既简单又简单。 How can I go about this? 我该怎么办? Date
object seems to get unnecessarily complicated in javascript. Date
对象似乎在javascript中变得不必要地复杂。
You need to override toJSON function of moment. 您需要重写一下toJSON函数。
Please see Moment Docs for more details, but basically you need to do something like this 请参阅Moment Docs了解更多详细信息,但基本上您需要执行以下操作
moment.fn.toJSON = function () {
return this.format('YYYY-MM-DDTHH:mm:ss'); //Or any desired format
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.