从前端到网络API问题的日期发布

时间:2017-04-24 03:01:09

标签: javascript asp.net-web-api

我有一些带有小时和分钟文本框字段的日历,用于在我的角度应用程序中捕获日期时间。

这会转换为完整日期,如下所示:

accidentVM.AccidentNotificationDateFull = new Date(accidentVM.AccidentNotificationDate.getFullYear(), accidentVM.AccidentNotificationDate.getMonth(), accidentVM.AccidentNotificationDate.getDate(),
                                                parseInt(accidentVM.AccidentNotificationHour), parseInt(accidentVM.AccidentNotificationMinute), 0);
var notificationDate = accidentVM.AccidentNotificationDateFull;

现在,如果我在web api中将此notificationDate作为输入发布,并且当它到达web api时会变得不同,因为javascript正在附加我的本地时区(即+ 5:30)。

要避免这种情况

我在客户端对GMT进行了调整。这基本上是记录了gmt偏移量,并从输入中减去或添加它,以便在到达服务器时再次正确。

该功能看起来像

this.convertDate = function (dateVM) {               
                var dateObj = dateVM;
                if (new Date().getTimezoneOffset() < 0) {
                    dateVM = new Date(dateObj.setTime(dateObj.getTime() - new Date().getTimezoneOffset() * 60 * 1000));
                }
                else {
                    dateVM = new Date(dateObj.setTime(dateObj.getTime() + new Date().getTimezoneOffset() * 60 * 1000));
                }                
};

这解决了这个问题,我现在看到了发布的正确日期时间,但是当它到达服务器时,它仍然会在结尾附加一个T.

从前端查看此处的输入 enter image description here

当它到达web api时就变成了

enter image description here

和相应的小提琴请求

enter image description here

如果您发现它已成为UTC,或者它最后附加了Z.

我的任务是,如果有任何办法我可以摆脱Z或更具体的DateTime种类应该是未指定/本地?

1 个答案:

答案 0 :(得分:0)

我在WebApiConfig类中添加了以下本地日期格式设置。这将告诉web api json格式化程序转换为本地时区。

var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
因此,我不需要明确的客户端操纵GMT。