.NET Core如何将时间数据格式化

 在进行前后端数据交互时发现前端无法正常显示时间信息:

 此时我们在后端进行数据的处理:

  1. 1. 给项目安装包Microsoft.AspNetCore.Mvc.NewtonsoftJson
  2. 2.注入服务
builder.Services.AddControllers().AddNewtonsoftJson(option =>
{
    option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});

此时发现时间可以正常显示了:

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
.Net Core 中,你可以通过实现一个继承自 `ActionFilterAttribute` 的过滤器来实现全局的日期格式化。具体步骤如下: 1. 创建一个继承自 `ActionFilterAttribute` 的过滤器类,比如 `DateFormatFilter`。 ```csharp public class DateFormatFilter : ActionFilterAttribute { private readonly string _format; public DateFormatFilter(string format) { _format = format; } public override void OnResultExecuting(ResultExecutingContext context) { if (context.Result is ObjectResult objectResult) { objectResult.Value = HandleObject(objectResult.Value); } else if (context.Result is JsonResult jsonResult) { jsonResult.Value = HandleObject(jsonResult.Value); } else if (context.Result is ContentResult contentResult) { contentResult.Content = HandleContent(contentResult.Content); } base.OnResultExecuting(context); } private object HandleObject(object obj) { if (obj == null) { return null; } var objectType = obj.GetType(); if (objectType.IsValueType || objectType == typeof(string)) { return obj; } var properties = objectType.GetProperties(); foreach (var property in properties) { if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?)) { var value = property.GetValue(obj); if (value != null) { var dateTime = (DateTime)value; property.SetValue(obj, dateTime.ToString(_format)); } } } return obj; } private string HandleContent(string content) { // TODO: 处理 ContentResult 的内容 return content; } } ``` 2. 在 `Startup.cs` 文件中注册过滤器。 ```csharp public void ConfigureServices(IServiceCollection services) { // 注册全局日期格式化过滤器 services.AddMvc(options => { options.Filters.Add(new DateFormatFilter("yyyy-MM-dd HH:mm:ss")); }); } ``` 这样,无论你的 WebApi 返回的数据JSON、XML 还是纯文本,都会按照指定的日期格式进行格式化

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.net开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值