您的位置:首页 > 移动开发 > 微信开发

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

2018-03-23 15:51 621 查看
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.jsconst 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, formatDa
4000
te: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  
    });  
  }    
})  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: