c# mvc/webpai全域性設定時間格式都返回時間戳
這裡用Newtonsoft舉例
1、nuget新增引用
Newtonsoft.Json
Microsoft.AspNetCore.Mvc.NewtonsoftJson
2、.net5及以下在Startup.net6在Program在AddControllers後新增AddNewtonsoftJson
.net5:
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.UnixDateTimeConverter());
});
.net6:
builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.UnixDateTimeConverter());
});
執行
這樣所有的時間格式在返回前端都會變成時間戳,不過這裡的時間戳的精度是秒,10位,假如需要毫秒的話需要自定義一個CustomUnixDateTimeConverter
我們可以參考UnixDateTimeConverter的實現
看了UnixDateTimeConverter的原始碼發現他用的單位是秒,我們只需要將秒改為毫秒就行了
以下是改造後的程式碼,異常我只是簡單的處理了一下有需要的可以自己處理
namespace Newtonsoft.Json.Converters
{
public class CustomUnixDateTimeConverter : DateTimeConverterBase
{
internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
long num;
if (value is DateTime)
{
num = (long)(((DateTime)value).ToUniversalTime() - UnixEpoch).TotalMilliseconds;
}
else
{
if (!(value is DateTimeOffset))
{
throw new JsonSerializationException("Expected date object value.");
}
num = (long)(((DateTimeOffset)value).ToUniversalTime() - UnixEpoch).TotalMilliseconds;
}
if (num < 0)
{
throw new JsonSerializationException("Cannot convert date value that is before Unix epoch of 00:00:00 UTC on 1 January 1970.");
}
writer.WriteValue(num);
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool flag = IsNullable(objectType);
if (reader.TokenType == JsonToken.Null)
{
if (!flag)
{
throw new Exception("Cannot convert null value to {0}.");
}
return null;
}
long result;
if (reader.TokenType == JsonToken.Integer)
{
result = (long)reader.Value;
}
else
{
if (reader.TokenType != JsonToken.String)
{
throw new Exception( "Unexpected token parsing date. Expected Integer or String, got.");
}
if (!long.TryParse((string)reader.Value, out result))
{
throw new Exception ( "Cannot convert invalid value to.");
}
}
if (result >= 0)
{
DateTime unixEpoch = UnixEpoch;
DateTime dateTime = unixEpoch.AddMilliseconds(result);
if ((flag ? Nullable.GetUnderlyingType(objectType) : objectType) == typeof(DateTimeOffset))
{
return new DateTimeOffset(dateTime, TimeSpan.Zero);
}
return dateTime;
}
throw new Exception("Cannot convert value that is before Unix epoch of 00:00:00 UTC on 1 January 1970 to.");
}
private static bool IsNullable(Type t)
{
if (t.IsValueType)
{
return IsNullableType(t);
}
return true;
}
private static bool IsNullableType(Type t)
{
if (t.IsGenericType)
{
return t.GetGenericTypeDefinition() == typeof(Nullable<>);
}
return false;
}
}
}
將之前的UnixDateTimeConverter換成換成CustomUnixDateTimeConverter執行
ok,時間戳精度到毫秒了