微信小程序动态获取当前时间显示到页面

岁酱吖の 提交于 2020-02-25 16:39:40

index/index.wxml

<!--index.wxml-->
<view class="container">
  <!-- 建立按钮,为按钮绑定函数 -->
  <button bindtap="getTime">点击获取当前时间</button>
  <!-- wx:if判断是否存在 -->
  <text wx:if="{{time}}">{{time}}</text>
</view>

 index/index.js

//index.js
var util = require('../../utils/util.js');
Page({
  data: {
  },
  //给按钮绑定getTime事件
  getTime:function(){
    var time = util.formatTime(new Date())
    //为页面中time赋值
    this.setData({
      time:time
    })
    //打印
    console.log(time)
  }
})

utils/util.js

// utils/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
}

 

注意点:1.通过bindtap为按钮绑定函数。

              2.wx:if 判断 {{time}} 值是否为空,空则不显示。

              3.调用util.js中的formatTime完成时间对象的创建与赋值。

              4.setData方法为页面中 {{time}} 赋值。
 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!