webapi 统一处理时间格式

2021-06-07 23:04

阅读:683

标签:orm   alt   out   oda   timezone   control   timestamp   rto   json   

public class UnixDateTimeConvertor : DateTimeConverterBase
    {

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {

            return DateTime.Parse(reader.Value.ToString());
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            //long timeStamp = (long)(((DateTime)value) - startTime).TotalMilliseconds;
            writer.WriteValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter
            //{
            //    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            //});

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //设置Datetime 到 時間戳 的互轉 
            JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            };
            jSettings.Converters.Add(new UnixDateTimeConvertor());
            config.Formatters.JsonFormatter.SerializerSettings = jSettings;

        }
    }

 

webapi 统一处理时间格式

标签:orm   alt   out   oda   timezone   control   timestamp   rto   json   

原文地址:https://www.cnblogs.com/liuqiyun/p/10729338.html


评论


亲,登录后才可以留言!