.Net Json序列化日期/Date(xxxx)/的Js转化&C#转化

来源:互联网 发布:java程序员进阶之路 编辑:程序博客网 时间:2024/05/16 16:08

1..Net中对于日期格式化结果都是 /Date(xxxx)/ 的格式,然而xxxx是指定时间距离标准时间(UTC)的总得毫秒数 (1970.1.1 00:00:00.000)

处理方式说明:使用正则表单时匹配出总毫秒数,然后进行日期转化

正则内容:

//只获取正整数部分,不考虑大于1970年问题string p = @"\\/Date\((\d+)\)\\/";//考虑小于1970年的问题string p = @"\\/Date\((-*\d+)\)\\/";

一、前台JS处理

转化成 Js Date对象

var str = '/Date(1464941268937)/';var date = new Date(1464941268937);console.info(date.toString());var date2 = new Date(1464941268937);console.info(date2.toLocaleString());var date3 = eval(str.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));console.info(date3);


2.对Date对象格式化处理方法

var date = new Date(1464941268937 + 0800);Date.prototype.format = function (format) {    var o = {        "M+": this.getMonth() + 1, //month         "d+": this.getDate(), //day         "h+": this.getHours(), //hour         "m+": this.getMinutes(), //minute         "s+": this.getSeconds(), //second         "q+": Math.floor((this.getMonth() + 3) / 3), //quarter         "S": this.getMilliseconds() //millisecond     }    if (/(y+)/.test(format)) {        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));    }    for (var k in o) {        if (new RegExp("(" + k + ")").test(format)) {            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));        }    }    return format;}document.write(date.format("yyyy-MM-dd hh:mm:ss"));document.write('<br />');document.write(date.format("yyyy年MM月dd日"));

二、后台C#处理方式

//string str = DateTime.Now.ToJsonString();// string str = @"\/Date(1464941268937)\/";string str = @"\/Date(-349776000000)\/";//只获取正整数部分,不考虑大于1970年问题string p = @"\\/Date\((\d+)\)\\/";//考虑小于1970年的问题string p = @"\\/Date\((-*\d+)\)\\/";Regex reg = new Regex(p);Match match = reg.Match(str);Console.WriteLine(ConvertJsonDateToDateString(match));
处理方法:

/// <summary>    /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串    /// </summary>    private static string ConvertJsonDateToDateString(Match m){    string result = string.Empty;    DateTime dt = new DateTime(1970, 1, 1);    dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));    dt = dt.ToLocalTime();    result = dt.ToString("yyyy-MM-dd HH:mm:ss");    return result;}


关于UTC(全球标准时间)

UTC 即全球标准时间,是全球范围内计时的科学标准。它基于精心维护的原子钟,在全球范围内精确到微秒。由于地球旋转的不规则性,每年有两次机会根据需要增减跳跃秒数,以调整 UTC。作为全球最精确的时间系统,天文学家、航海家、“太空跟踪网”(DSN) 以及其他科学性学科都使用它。它的参考点是英国格林威治:地球本初子午线的午夜,也是 UTC 的午夜 (00:00:00.000000) 

现在计算机和一些电子设备时间的计算和显示是以距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量为标准的,如1970-1-10 20:47 偏移量为2724441632毫秒,出现类似字样说明时间被初始化了。


0 1