C# 仍然在为JSON.net Dateformat苦苦挣扎
我在将日期(字符串格式)传输到对象中时遇到问题,因为序列化程序似乎总是将其转换为错误 格式实际上是C# 仍然在为JSON.net Dateformat苦苦挣扎,c#,asp.net,json,json.net,C#,Asp.net,Json,Json.net,我在将日期(字符串格式)传输到对象中时遇到问题,因为序列化程序似乎总是将其转换为错误 格式实际上是dd.MM.yyyy(瑞士时间格式),序列化程序尝试将其转换为MM dd yyyy(其中日期将转换为月份) 因此,如果我有一个日期,如1992年3月6日(3月6日),转换器将其定为6月3日。 如果一天超过12天,程序就会完全崩溃 我知道我可以以某种方式指定日期格式,但我还没有一个有效的解决方案。 对我的问题有什么想法吗 提前感谢,, Daniel很有可能.net将日期序列化如下: \/Date(12
dd.MM.yyyy
(瑞士时间格式),序列化程序尝试将其转换为MM dd yyyy
(其中日期将转换为月份)
因此,如果我有一个日期,如1992年3月6日(3月6日),转换器将其定为6月3日。
如果一天超过12天,程序就会完全崩溃
我知道我可以以某种方式指定日期格式,但我还没有一个有效的解决方案。
对我的问题有什么想法吗
提前感谢,,
Daniel很有可能.net将日期序列化如下:
\/Date(1293034567877)\/
您需要解析该日期并手动安排它:
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return ((month > 9 ? month : "0" + month) + "/" + (day > 9 ? day : "0" + day) + "/" + year);
};
或者在您的情况下,函数将返回:
return ((day > 9 ? day : "0" + day) + "." + (month > 9 ? month : "0" + month) + "." + year);
通过创建
IsoDateTimeConverter
类的新实例,根据需要对其设置DateTimeFormat
属性,然后将转换器传递给序列化程序,可以控制Json.Net用于序列化和反序列化日期的格式
下面是一个演示:
class Program
{
static void Main(string[] args)
{
IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
{
DateTimeFormat = "dd.MM.yyyy"
};
Foo foo = new Foo { Date = new DateTime(2014, 3, 12) };
// serialize an object containing a date using the custom date format
string json = JsonConvert.SerializeObject(foo, dateConverter);
Console.WriteLine(json);
// deserialize the JSON with the custom date format back into an object
Foo foo2 = JsonConvert.DeserializeObject<Foo>(json, dateConverter);
Console.WriteLine("Day = " + foo2.Date.Day);
Console.WriteLine("Month = " + foo2.Date.Month);
Console.WriteLine("Year = " + foo2.Date.Year);
}
}
class Foo
{
public DateTime Date { get; set; }
}
注意:使用这种方法,日期格式将应用于正在序列化或反序列化的所有对象上的所有日期。如果您需要不同日期的不同格式,请查看哪种格式提供了两种可能的解决方案。read和dates没有格式。格式在序列化为字符串时起作用。没有标准的JSON日期格式,只有约定。最流行的是Javascript的
Date.ToJSON
返回的。您提到的格式都与此不匹配。请发布显示问题的代码以及您使用的Json.Net版本。默认格式@jparram,在Json.NET 4.5之后,默认使用ISO 8601格式,即“2012-03-19T07:22Z”@PanagiotisKanavos,因此它是4.5之前的默认格式,之后是ISO 8601
{"Date":"12.03.2014"}
Day = 12
Month = 3
Year = 2014