微信小程序日期/时间格式化

1、微信自己提供的util中,有一个日期格式化的工具,如果要使用的话,请导入var util = require('../../utils/util.js'),然后关于util.formatTime(new Date)的使用,不要用Date.now(),请老老实实使用  new Date()。

2、因为使用的格式是yyyy-mm-dd,所以修改了util中的方法,仿照formatTime写了formatTime2,记得在module.exports中增加对应的定义。

unit.js

const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()

return [year, month, day].map(formatNumber).join( '/') + ' ' + [hour, minute, second].map(formatNumber).join( ':')
}
const formatDate = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()

return [year, month, day].map(formatNumber).join( '-')
}
const formatNumber = n => {
n = n.toString()
return n[ 1] ? n : '0' + n
}
const formatTimeNew = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [hour, minute].map(formatNumber).join( ':')
}
module.exports = {
formatTime: formatTime,
formatDate:formatDate,
formatTimeNew:formatTimeNew
}

html

<view>{{time}}</view>  

js

// 在需要使用的js文件中,导入js  
var util = require('../../utils/util.js');  
Page({  
  data: {  
  time:util.formatTime(new Date())
  },  
  onLoad: function () {  
    // 调用函数时,传入new Date()参数,返回值是日期和时间  
    var time = util.formatTime(new Date());  
    // 再通过setData更改Page()里面的data,动态更新页面的数据  
    this.setData({  
      time: time  
    });  
  }    
})  



猜你喜欢

转载自blog.csdn.net/weixin_40292626/article/details/79668543
今日推荐