webapi 统一处理时间格式
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; } }