Dynamics CRM2016 Web Api之时间字段值的处理

本篇又是一次来谈到CRM中时间字段的问题,那这次要谈的是在引用web api过程中写代码上的注意事项,常用的代码场景即JS和c#.

先来看下js,从下图中可以看到,我直接将new Date()赋值给时间字段时,经过json序列化后会将本地时间转化为国际时间,那如果我的时间字段的行为是无时区,写进后台数据库的就是国际时间那就是错误的,会有8小时的时差。

Dynamics CRM2016 Web Api之时间字段值的处理

那怎么办呢,我们想到的简单粗暴的方式就是new Date().toString()这样json处理的是字符串而不是时间就不会减8转化为国际时间了,但很不幸系统会报错“Cannot convert the literal 'Tue Jul 26 2016 12:11:47 GMT+0800 to the expected type 'Edm.DateTimeOffset”,格式不接收.

那我们要写成人家接收的格式呀,但JS不像C#可以直接toString("yyyy-MM-ddTHH:mm:ssZ"),人家不认的,那要怎么让人家认呢,引用下面的代码来重写Format,最后new Date().format("yyyy-MM-ddTHH:mm:ssZ")即可。

Date.prototype.Format = function(fmt)
{ //author: meizz
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
}
上一篇:收银台数据库存储AES加解密


下一篇:基于pytorch实现HighWay Networks之Train Deep Networks