实现时间格式化的封装:
如:在微信小程序中的用法做一个简单的示例,代码如下
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,format) => {
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()
format = format.replace(/yyyy/g, year);
format = format.replace(/MM/g, formatNumber(month));
format = format.replace(/dd/g, formatNumber(day));
format = format.replace(/hh/g, formatNumber(hour));
format = format.replace(/mm/g, formatNumber(minute));
format = format.replace(/ss/g, formatNumber(second));
return format;
}
const formatDateLastMonth = (date,format) => {
const year = date.getMonth() == 0 ? date.getFullYear() -1 : date.getFullYear();
const month = date.getMonth() == 0 ? 12 : date.getMonth();
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
format = format.replace(/yyyy/g, year);
format = format.replace(/MM/g, formatNumber(month));
format = format.replace(/dd/g, formatNumber(day));
format = format.replace(/hh/g, formatNumber(hour));
format = format.replace(/mm/g, formatNumber(minute));
format = format.replace(/ss/g, formatNumber(second));
return format;
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime,
formatDate: formatDate,
formatDateLastMonth: formatDateLastMonth
}
在其他页面中使用只需在该页面中require引入使用:
const util = require('../../utils/util.js')
如请求接口,从后台拿到数据经常需要我们做一些简单的处理:
ReqInter: function(){
// 加载提示
wx.showLoading()
wx.request({
// 请求路径
url: '/alarm/device/deviceList',
// 请求参数
data: {
id: 'that.options.id',
beginTime: 'that.data.startTime',
endTime: 'that.data.endTime',
type: '2'
},
// 请求方式默认为GET请求
motheds: 'GET'
// 请求成功的回调
success: function(res){
if(res.stutsCode == 200){
//console.log(res.data)
// 比如time是从接口i中拿到的时间
let time = res.data.createTime
//很不幸的是time是一个时间戳,
//我们要将他格式化成我们想要的时间格式要怎么做呢, 很简单往下看
// 取: 年月日 时分秒
let formatTime = util.formatDate(new Date(time), 'yyyy-MM-dd hh:mm:ss')
// 取: 年月日
let formatTime2 = util.formatDate(new Date(time), 'yyyy-MM-dd')
// 取: 时分秒
let formatTime3 = util.formatDate(new Date(time), 'hh:mm:ss')
// .....
}
wx.hiddeLoading()
},
// 请求失败的回调
fail: function(){
wx.hiddeLoading()
wx.showToast({
icon: 'none',
duration: 2500,
title: '接口调用失败',
})
}
})
}
最后不要忘了在onLoad中调用ReqInter