学习使用微信小程序动态获取当前时间并实时跳动
1、修改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
}
2、.js函数构造
//头部引用util.js
// pages/user/index.js
var util=require('../../utils/util');
Page({
/**
* 页面的初始数据
*/
data: {
Time:''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
setInterval(function(){
that.setData({
Time: util.formatTime(new Date())
});
},1000);
},
getTime:function(e){
var that = this;
var currentTime = util.formatTime(new Date());
},
})
我们需要在onLoad函数里面设置一个定时器,每过一秒钟就调用一次getTime函数,从而获取到实时的时间
3、wxml页面显示固定时间
<view bindtap="getTime" style="color:block;font-size: 25px;">时间 {{Time}}</view>