如何在没有/date的情况下格式化JSON日期

本文关键字:情况下 格式化 JSON 日期 date | 更新日期: 2023-09-27 17:59:31

我需要从以下格式格式化JSON日期:docDate":"1360905419116",","inDocDate":"136090541911 6"等。

我的连载:

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string result = jsonSerializer.Serialize( new {
    docDate = DateTime.Now,
    inDocDate = DateTime.Now,
    outDocDate = DateTime.Now } );

序列化后我收到的结果:

{"docDate":"'/Date(1360905419116)'/","inDocDate":"'/Date(1360905419116)'/","outDocDate":"'/Date(1360905419116)'/"}

我想要

{"docDate":"1360905419116","inDocDate":"1360905419116","outDocDate":"1360905419116"}

如何在没有/date的情况下格式化JSON日期

您可以使用此扩展方法

public static class DateTimeExtensions
{
  internal static readonly long DatetimeMinTimeTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  public static long ToJsTime(this DateTime dateTime)
  {
    return (dateTime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000L;
  }
}

所以你的代码变成了:

string result = jsonSerializer.Serialize( new {
    docDate = DateTime.Now.ToJsTime().ToString(),
    inDocDate = DateTime.Now.ToJsTime().ToString(),
    outDocDate = DateTime.Now.ToJsTime().ToString() } );