码迷,mamicode.com
首页 > Windows程序 > 详细

webapi 统一处理时间格式

时间:2019-04-18 14:49:04      阅读:333      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!