keep C# datetime local time between json and Web api?

前端 未结 3 1847
死守一世寂寞
死守一世寂寞 2021-02-05 12:55

I have problem when I have datatime in json object it will convert it to UTC time zone in C# dateTime just want to ask how to keep local time?can I set time zone property in w

相关标签:
3条回答
  • 2021-02-05 13:00

    You can use TimeZoneInfo.ConvertTime to convert to the wanted timezone.

    Checkout this method: https://msdn.microsoft.com/en-us/library/bb382770(v=vs.110).aspx

    0 讨论(0)
  • 2021-02-05 13:08

    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,
        };
    

    There is also various date format you can choose from : 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
    }
    
    0 讨论(0)
  • 2021-02-05 13:20

    You can configure this. See: http://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm

    Here's an example:

    public void Config(IAppBuilder app)
    {
        var config = new HttpConfiguration();
    
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
    
        app.UseWebApi(config);
    }
    
    0 讨论(0)
提交回复
热议问题