1. 程式人生 > 其它 >去掉時間格式(yyyy:MM:ddThh:mm:ss)中間的“T”的前後臺兩種方法

去掉時間格式(yyyy:MM:ddThh:mm:ss)中間的“T”的前後臺兩種方法

技術標籤:Asp.Net學習記錄asp.netvue.jsjavascript

問題展示如下,取出的時間中間含有T

[ 
 {
    "imgUrl": "http://localhost:44375/imgs/20201218/123.PNG",
    "id": 1,
    "loginId": 1,
    "loginName": "liubang",
    "name": "劉邦",
    "phone": "13713141222",
    "publishContent": "我劉邦賊牛皮",
    "createTime": "2020-04-09T00:00:00" //時間格式中含有T
  },
  {.....}]

後臺解決方法

startup.cs檔案中,在如下位置新增格式轉換程式碼

.....
public void ConfigureServices(IServiceCollection services)
{
  ......

   //JSON格式化
   services.AddMvc().AddNewtonsoftJson(options =>
   {
       options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
   });
       //引數.序列化設定.資料格式化字串=“規則”
      //AddNewtonsoftJson需要專案中引用一個包
}

在專案中NuGet包管理器中安裝一個包:Newtonsoft

安裝後位置如下:

前臺解決方法

在JS中,對獲取的時間進行正則表示式修飾即可.replace(/T/g, ' ').replace(/.[\d]{3}Z/, ' ')

缺點:每次用到都要進行修飾,太過於繁瑣,不推薦

示例一:

getData() {
    wx.request({
      url: 'http://[ip]/api/PublishViews',
      success(res) {
        console.log(res.data)
        var temp = res.data
        for (var i = 0; i < temp.length; i++)
        {
          temp[i].createTime=temp[i].createTime.replace(/T/g, ' ').replace(/.[\d]{3}Z/, ' ');      
        }          
        that.setData({
          posts: temp,         
        })
        wx.hideLoading({})
        wx.stopPullDownRefresh({}) 
      }
    })
  },

示例二:

onLoad: function (options) {
    that = this
    wx.request({
      url: 'http://[ip]/api/PublishViews/'+options.id,
      success(res) {
        that.setData({
          ....
          dateTime:res.data.createTime.replace(/T/g, ' ').replace(/.[\d]{3}Z/, ' '),
          ....
        })

      }
    })
  },