1,829 次浏览

如何将 .NET DateTime 转换为 JavaScript Date – 形如:\/Date(1539953962642)\/

前言

在使用 ASP.NET MVC 开发 Web 程序时,对于 DateTime 类型的数据在 JSON 结果中,以类似于 “\/Date(1539953962642)\/” 的形式进行返回,那么这里中格式叫做什么呢?其中的数字的意义如何?

实际上这种数据格式叫做 Microsoft’s built-in JSON Date format,这不是任何一个通用规范的一部分,它是微软定义的一种格式。并且这里的数字并不是 .NET DateTime 的 Ticks!实际上这个值就是 TimeInMillis!


Ticks 和 TimeInMillis 有什么区别?

Ticks 一般是指从 0001-01-01 00:00:00.000 到现在的百纳秒计数,这个计数单位是 100 nanosecond(long 类型存储),.NET 平台使用 Ticks 方式记录时间(比如 [C#] DateTime.UtcNow.Ticks)。

TimeInMillis 一般是指从 1970-01-01 00:00:00.000 到现在的毫秒数,这个单位是 1 millisecond(long 类型存储),Java 和 JavaScript 使用 TimeInMillis 方式记录时间(比如 [JavaScript] Date.now())

所以,我们只需要通过正则表达式提取这个 Microsoft’s built-in JSON Date format 的值,直接应用于 JavaScript 即可。


识别 \/Date(1539953962642)\/

// The value of ticksString like "\/Date(1539953962642)\/";
function MicrosoftJsonDateFormatStringToTimeInMillis(ticksString) {
    var ticks = ticksString.replace(/[^0-9]/ig, "");
    return new Date(parseInt(ticks));
};


TimeInMillis to Ticks

至于如何将 TimeInMillis 转换为 Ticks 网上的资料非常多,基本就是:

// The date is your JavaScript Date object
function TimeInMillisToTicks(date) {
    // There are 10000 ticks in a millisecond. And 621.355.968.000.000.000 ticks between 1st Jan 0001 and 1st Jan 1970.
    return ((yourDateObject.getTime() * 10000) + 621355968000000000);
}


好人做到底 – JavaScript Date Format

// *** 本代码原作者 meizz ***
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
    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;
}

参考资料:
https://stackoverflow.com/questions/206384/how-do-i-format-a-microsoft-json-date

About nista

THERE IS NO FATE BUT WHAT WE MAKE.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注