首先我们要用到的是微信小程序官方给的两个函数,在util.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 formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime
}
其中formatTime这个函数返回的值中,你也可以把 '-' 改成 '/' ,这样显示的就是 2018/8/20 16:27:30 了
有了这个,我们在其他页面调用时间的时候就只需要引用util.js文件,即可调用。
引用和调用方法:
//引用方法
var util = require("../../utils/util.js");
//调用方法:
//只需要传入new Date
console.log(util.formatTime(new Date));
下面是我写的给当前时间加减小时。也放在util.js文件中,然后在module.exports中也要声明你的函数,这样才能被引用出去。
const endFormatTime = (date, x) => {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours() + x
var minute = date.getMinutes()
var second = date.getSeconds()
if(hour >= 24){
hour -= 24;
day += 1;
}
if(hour < 0){
hour += 24;
day -= 1;
}
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
module.exports = {
formatTime: formatTime,
endFormatTime: endFormatTime
}
调用这个函数的时候,第二个参数x是小时数,那就酱~
希望我的记录能够帮到你~ 喜欢请点赞!
谢谢你看到这里!写作仓促,有疏漏之处还请评论指正,共同探讨进步!