/Date(-62135596800000)/ 如何转换成C# 时间

今天在项目中遇到返回的JSON 串中遇到时间无法转的情况。
如下字符串
/Date(-62135596800000)/

/Date(-62135596800000)/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace DemoLibrary
{
public class JsonManage
{
/// 
/// JSON序列化
/// 
/// 
/// 
public static string JsonSerializer(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms,t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
string pattern = @"\/Date((\d+)+\d+)\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(pattern);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
/// 
/// JSON反序列化
/// 
/// 
/// 
public static T JsonDeserialize(string jsonString)
{
string pattern = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(pattern);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
/// 
/// 将Json序列化的时间由/Date(1304931520336+0800)/转为字符串
/// 
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;
}
/// 
/// 将时间字符串转为Json时间
/// 
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\/Date({0}+0800)\/",ts.TotalMilliseconds);
return result;
}
}
}

时间戳的问题可以在http://tool.chinaz.com/tools/unixtime.aspx 这里转换 但你这个数值。。。。

时间戳的问题可以在http://tool.chinaz.com/tools/unixtime.aspx 这里转换 但你这个数值。。。。

两种方法:

1、js格式转换

$(function() { $.getJSON("getJson.ashx", function (students) { $.each(students, function (index, obj) { $("<li/>").html(obj.Name).appendTo("#ulStudents"); //使用正则表达式将生日属性中的非数字(\D)删除 //并把得到的毫秒数转换成数字类型 var birthdayMilliseconds = parseInt(obj.Birthday.replace(/\D/igm, "")); //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数 var birthday = new Date(birthdayMilliseconds); $("<li/>").html(birthday.toLocaleString()).appendTo("#ulStudents"); ; }); }); });

2、在后台传值之前不使用datetime格式的数据,转而试用string字符串格式,不会发生这种错误

在项目中我一般是写一个js文件来序列化时间格式
var Common = {
/**
* 格式化日期(不含时间)
/
formatterDate: function (date) {
if (date == undefined) {
return "";
}
/*json格式时间转js时间格式
/
date = date.substr(1, date.length - 2);
var obj = eval('(' + "{Date: new " + date + "}" + ')');
var date = obj["Date"];
if (date.getFullYear() < 1900) {
return "";
}

    var datetime = date.getFullYear()
            + "-"// "年"
            + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0"
                    + (date.getMonth() + 1))
            + "-"// "月"
            + (date.getDate() < 10 ? "0" + date.getDate() : date
                    .getDate());
    return datetime;
},
/**
 * 格式化日期(含时间"00:00:00")
 */
formatterDate2: function (date) {
    if (date == undefined) {
        return "";
    }
    /*json格式时间转js时间格式*/
    date = date.substr(1, date.length - 2);
    var obj = eval('(' + "{Date: new " + date + "}" + ')');
    var date = obj["Date"];
    if (date.getFullYear() < 1900) {
        return "";
    }

    /*把日期格式化*/
    var datetime = date.getFullYear()
            + "-"// "年"
            + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0"
                    + (date.getMonth() + 1))
            + "-"// "月"
            + (date.getDate() < 10 ? "0" + date.getDate() : date
                    .getDate()) + " " + "00:00:00";
    return datetime;
},
/**
 * 格式化去日期(含时间)
 */
formatterDateTime: function (date) {
    if (date == undefined) {
        return "";
    }
    /*json格式时间转js时间格式*/
    date = date.substr(1, date.length - 2);
    var obj = eval('(' + "{Date: new " + date + "}" + ')');
    var date = obj["Date"];
    if (date.getFullYear() < 1900) {
        return "";
    }

    var datetime = date.getFullYear()
            + "-"// "年"
            + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0"
                    + (date.getMonth() + 1))
            + "-"// "月"
            + (date.getDate() < 10 ? "0" + date.getDate() : date
                    .getDate())
            + " "
            + (date.getHours() < 10 ? "0" + date.getHours() : date
                   .getHours())
            + ":"
            + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date
                    .getMinutes())
            + ":"
            + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date
                    .getSeconds());
    return datetime;
}

};

调用的时候 直接把json时间传进去就会自己序列化了 Common.formatterDateTime(value)