序列化了一组json数据,得到的日期的值不会处理了!
C# code
List<NUser> list = new List<NUser>();
NUser item = null;
for (int i = 1; i < 10; i++)
{
item = new NUser();
item.ID = i;
item.Name = i + "_Name";
item.Time = DateTime.Now.AddDays(i * -1);
list.Add(item);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
result = serializer.Serialize(list);
context.Response.Write(result);
context.Response.End();
ajax请求上面的代码,返回一组序列化好的json数据,在前台接收到之后,result[0].Time的值是: "/Date(1335230881375)/"
怎么用js处理成我想要的格式啊? 格式:2012-4-25 9:29:21
------解决方案--------------------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 ;
}
------解决方案--------------------在你后台序列化时候不要用datetime类型,直接用string类型,然后序列化,在前台反序列化就不会出现这个问题了
也就是在你的NUser类中这么设置属性string date,你的应该是datetime date
------解决方案--------------------参考
http://kb.cnblogs.com/a/2365098/
------解决方案--------------------using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace HKH.Web.MVC
{
public class DateTimeHelper
{
/// <summary>
/// Parse Json data string to C# DateTime
/// </summary>
/// <param name="jsonDate"></param>
/// <returns></returns>
public static DateTime FromJson(string jsonDate)
{
return FromJson(jsonDate, DateTimeKind.Local);
}
/// <summary>
/// Parse Json data string to C# DateTime
/// </summary>
/// <param name="jsonDate">&l