且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

保持JSON和Web API之间的C#日期时间本地时间?

更新时间:2023-02-08 09:59:49

您可以更改序列化程序设置使用JSON.net序列化器:

You can change your serializer settings to use the JSON.net serializer :

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = 
    new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.IsoDateFormat,
        DateTimeZoneHandling = DateTimeZoneHandling.Unspecified,
    };




您还可以选择多种日期格式: DateTimeZoneHandling

/// <summary>
/// Specifies how to treat the time value when converting between string and <see cref="DateTime"/>.
/// </summary>
public enum DateTimeZoneHandling
{
    /// <summary>
    /// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time.
    /// </summary>
    Local = 0,

    /// <summary>
    /// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC.
    /// </summary>
    Utc = 1,

    /// <summary>
    /// Treat as a local time if a <see cref="DateTime"/> is being converted to a string.
    /// If a string is being converted to <see cref="DateTime"/>, convert to a local time if a time zone is specified.
    /// </summary>
    Unspecified = 2,

    /// <summary>
    /// Time zone information should be preserved when converting.
    /// </summary>
    RoundtripKind = 3
}