小程序:获取动态时分秒时钟

效果如

在这里插入图片描述

实现过程

js:

const app = getApp()
import util from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    todayTime: '', // 获取当前时间
    realTime: '',


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.gettodayTime() // 获取当前时间
  },

   // 获取当前时间
   gettodayTime(){
      // 调用函数时,传入new Date()参数,返回值是时间
      var time = util.formatTodayTime(new Date());
      this.setData({
        todayTime: time // 页面展示的时分秒数据
      });
   }, 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var that = this
    this.data.realTime = setInterval(function()
      {
        that.gettodayTime()
      }, 1000)//间隔时间 1s
    // 更新数据
    this.setData({
      realTime:this.data.realTime,//实时数据对象(用于关闭实时刷新方法)
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
     /**
     * 当页面隐藏时关闭定时器(关闭实时刷新)
     * 切换到其他页面了
     */
    clearInterval(this.data.realTime)

  },
 
})

util.js

//展示时分秒
const formatTodayTime = date => {
 
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [hour, minute, second].map(formatNumber).join(':')
}

module.exports = {
  formatTodayTime: formatTodayTime,
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值