Json 的日期格式转换成DateTime

时间:2014-05-07 19:56:52   收藏:0   阅读:620

JSON 的日期形式:”/Date(1242357713797+0800)/” , 下面我们就用以下C#的方法将他转换成DateTime类型:


/// <summary>
/// Json 的日期格式与.Net DateTime类型的转换
/// </summary>
/// <param name="jsonDate">Json 的日期,例如:/Date(928120800000+0800)/</param>
/// <returns></returns>
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;
}

Json 的日期格式转换成DateTime,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!