Newtonsoft.Json时间转换

public class LogEntry
{
  public string Details { get; set; }
  public DateTime LogDate { get; set; }
}

public void WriteJsonDates()
{
  LogEntry entry = new LogEntry
  {
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
    Details = "Application started."
  };

  // default as of Json.NET 4.5
  string isoJson = JsonConvert.SerializeObject(entry);
  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

  JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
  {
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  };
  string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
  // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}

  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
  // {"Details":"Application started.","LogDate":new Date(1234656000000)}

IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
var customerJson  = JsonConvert.SerializeObject(entry, timeConverter);
  // {"Details":"Application started.","LogDate":"2016-01-01 11:22:33"}
}

你可能感兴趣的:(C#)