问题:
在页面上显示当前时间(日期)
方法:
1、在util.js (创建项目自动生成)中:
1 // util.js 2 const formatTime = date => { 3 const year = date.getFullYear() 4 const month = date.getMonth() + 1 5 const day = date.getDate() 6 const hour = date.getHours() 7 const minute = date.getMinutes() 8 const second = date.getSeconds() 9 10 return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute].map(formatNumber).join(':') //返回年月日,时分秒 11 } 12 13 const formatNumber = n => { 14 n = n.toString() 15 return n[1] ? n : '0' + n 16 } 17 18 module.exports = { 19 formatTime: formatTime 20 }
2、index.wxml 中写一个text显示时间
1 <text class="user-motto">{{time}}</text>
3、index.js中写逻辑
1 // index.js 2 3 var util = require('../../utils/util.js'); 4 Page({ 5 ...................... 6 /** 7 * 生命周期函数--监听页面加载 8 */ 9 onLoad: function (options) { 10 //日期显示 11 var time = util.formatTime(new Date()) 12 //为页面中time赋值 13 this.setData({ 14 time: time 15 }) 16 }, 17 ............................ 18 })
4、重点:require 官方链接:https://developers.weixin.qq.com/minigame/dev/reference/api/require.html
any require(string path)
引入模块。返回模块通过
module.exports
或exports
暴露的接口。
名称 类型 说明 path string 需要引入模块文件相对于当前文件的相对路径,或npm模块名,或npm模块路径。不支持绝对路径