首先,在pages外,创建一个utils文件夹模块
在其中添加一个utils.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
}
function sayHello(name) {
console.log(`Hello ${name} !`)
}
module.exports = {
formatTime:formatTime,
sayHello:sayHello
}
则,formatTime和sayHello可以作为函数供其它页面调用使用。
以index.js为例
在文件开头加上引用utils.js声明后
var utils= require('../../utils/utils.js')
就可以在函数体中加入utils具体使用了
console.log(utils.sayHello('index.js 测试 sayHello 函数'))
或
var time = utils.formatTime(new Date())
console.log(time)
time = time.split("/", 2)[1]
console.log(time)
以上的time可以作为变量在其它地方使用。
其他资料:
记录微信小程序显示当前年月日及其详细时间的代码 - 教程笔记 - 李洋个人博客
微信小程序--多种类型日期选择器(年月、月日...)_yoga今天敲代码了吗的博客-CSDN博客_微信小程序日期选择器