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

本文详细介绍了一个小程序中实现时间显示的方法,包括使用bindtap为按钮绑定函数,利用wx:if判断条件渲染,调用formatTime函数格式化日期,以及通过setData更新页面数据。此实践涵盖了小程序开发中的关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

整体结构:

               

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值