.net core 中 DateTime 序列化为json后带字母T问题

个人网站: yedajiang44.com

当实体类中的类型为DateTime类型时(如下)


   
   
  1. //实体
  2. class Model{
  3. //...
  4. //创建时间
  5. public DateTime CreateTime{get; set;}
  6. //...
  7. } 复制代码

再进行json序列化后,前端收到的结果为xxxx-xx-xxT xx:xx:xx 如:2018-11-03T15:20:20

原因是core版本中的Newtonsoft.Json默认使用的是ISO格式

解决办法:

第一种:后端指定序列化为时间戳,前端自己根据需要转换格式

1、打开Startup.cs文件,在ConfigureServices方法中添加如下代码


  
  
  1. public void ConfigureServices(IServiceCollection services){
  2. //....其他代码
  3. //需要添加的代码开始
  4. services.AddMvc().AddJsonOptions(option=>{
  5. //配置序列化首字母大小写问题,默认是首字母小写 option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
  6. //配置序列化时时间格式为时间戳
  7. option.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
  8. })
  9. //需要添加的代码结束
  10. } 复制代码

2、前端格式化时间格式代码


  
  
  1. ( function () {
  2. //日期扩展
  3. Date.prototype.format = function (fmt) {
  4. var o = {
  5. "M+": this.getMonth() + 1, //月份
  6. "d+": this.getDate(), //日
  7. "H+": this.getHours(), //小时
  8. "m+": this.getMinutes(), //分
  9. "s+": this.getSeconds(), //秒
  10. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  11. "S": this.getMilliseconds() //毫秒
  12. };
  13. if (/(y+)/. test(fmt))
  14. fmt = fmt.replace(RegExp. $1, (this.getFullYear() + "").substr(4 - RegExp. $1.length));
  15. for (var k in o) {
  16. if (o.hasOwnProperty(k)) {
  17. if (new RegExp( "(" + k + ")"). test(fmt))
  18. fmt = fmt.replace(RegExp. $1, (RegExp. $1.length === 1) ? (o[k]) : (( "00" + o[k]).substr(( "" + o[k]).length)));
  19. }
  20. }
  21. return fmt;
  22. };
  23. //字符串扩展
  24. String.prototype.getDate = function () {
  25. console.log(this)
  26. var res = /\d{13}/. exec(this);
  27. var date = new Date(parseInt(res));
  28. return date.format( "yyyy-MM-dd HH:mm:ss");
  29. }
  30. })(); 复制代码

3、前端接收到后台的时间戳字符串后调用


  
  
  1. let timeString= "1541243166"//该值应该为后台传过来的时间戳,为演示,这里指定固定值
  2. console.log(timeString.getDate();)//输出结果为:2018-11-03 19:06:06 复制代码

第二种:后端更改为指定字符串格式如:yyyy-MM-dd HH-mm-ss

1、打开Startup.cs文件,在ConfigureServices方法中添加如下代码


  
  
  1. public void ConfigureServices(IServiceCollection services){
  2. //....其他代码
  3. //需要添加的代码开始
  4. services.AddMvc().AddJsonOptions(option=>{
  5. //配置序列化首字母大小写问题,默认是首字母小写
  6. option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
  7. //配置序列化时时间格式为yyyy-MM-dd HH:mm:ss
  8. option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  9. })
  10. //需要添加的代码结束
  11. } 复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值