Json 的日期格式转换成DateTime

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;
}

你可能感兴趣的:(DateTime)