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

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}} 赋值。

整体结构:

               

猜你喜欢

转载自blog.csdn.net/qq_42751377/article/details/82717895