好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

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

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

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


static void 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(); } public static 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 +")");

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于Json 的日期格式与.Net DateTime类型的转换的详细内容...

  阅读:43次