问题
在页面上显示当前时间(日期)
方法
1、在util.js (创建项目自动生成)中:
// 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].map(formatNumber).join(':') //返回年月日,时分秒
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime
}
2、index.wxml 中写一个text显示时间
<text class="user-motto">{{time}}</text>
3、index.js中写逻辑
// index.js
var util = require('../../utils/util.js');
Page({
......................
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//日期显示
var time = util.formatTime(new Date())
//为页面中time赋值
this.setData({
time: time
})
},
............................
})
4、重点:require 官方链接
any require(string path)
引入模块。返回模块通过 module.exports 或 exports 暴露的接口。
| 名称 | 类型 | 说明 |
|---|---|---|
| path | string | 需要引入模块文件相对于当前文件的相对路径,或npm模块名,或npm模块路径。不支持绝对路径 |
