Fork me on GitHub
Json 的日期格式与.Net DateTime类型的转换

Json 的日期格式与.Net DateTime类型的转换

Json 的日期形式大概是这样:"/Date(1242357713797+0800)/" , 甭管它的格式是多么不友好(因为单从形式看根本不知道何年何月),如果这个Date只是一个属性的话, Json.Net 已经为我们处理好了。但有些很特殊的时候,需要单独把这个Date转换为.Net的DateTime格式,那么下面的代码就可以帮到你了。这个代码我已经找了很多次,终于被我发现了,免去重复造轮子的劳动。

这里跟大家分享一下, 可以保留毫秒,完全与原来结果一致。


staticvoid Main(string[] args) { string [] jsonDates = {"/Date(1242357713797+0800)/" , "/Date(1242357722890+0800)/"}; foreach (string jsonDate in jsonDates) { Console.WriteLine("Json : {0}", jsonDate); DateTime dtResult = JsonToDateTime(jsonDate); Console.WriteLine("DateTime: {0}", dtResult.ToString("yyyy-MM-dd hh:mm:ss ffffff")); } Console.Read(); } publicstatic DateTime JsonToDateTime(string jsonDate) { string value = jsonDate.Substring(6, jsonDate.Length -8); DateTimeKind kind = DateTimeKind.Utc; int index = value.IndexOf('+', 1); if (index ==-1) index = value.IndexOf('-', 1); if (index !=-1) { kind = DateTimeKind.Local; value = value.Substring(0, index); } long javaScriptTicks =long.Parse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); long InitialJavaScriptDateTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks; DateTime utcDateTime =new DateTime((javaScriptTicks *10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc); DateTime dateTime; switch (kind) { case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Local: dateTime = utcDateTime.ToLocalTime(); break; default: dateTime = utcDateTime; break; } return dateTime ; }

结果如下:



原文地址:http://www.cnblogs.com/coolcode/archive/2009/05/22/1487254.html

var text = data.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
return eval("("+ text +")");

posted on 2012-04-20 16:24  HackerVirus  阅读(374)  评论(0编辑  收藏  举报