微信小程序—显示当前时间

问题#

  在页面上显示当前时间(日期)

方法#

  1、在util.js (创建项目自动生成)中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  // 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].map(formatNumber).join(':')   //返回年月日,时分秒
}
 
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
 
module.exports = {
  formatTime: formatTime
}

  2、index.wxml 中写一个text显示时间

1
<text class="user-motto">{{time}}</text>

  3、index.js中写逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// index.js
  
 var util = require('../../utils/util.js');
 Page({
  ......................
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
    //日期显示
    var time = util.formatTime(new Date())
    //为页面中time赋值
    this.setData({
      time: time
    })
  },
 ............................
})

  4、重点:require  官方链接

any require(string path)

引入模块。返回模块通过 module.exports 或 exports 暴露的接口。

名称类型说明
path string 需要引入模块文件相对于当前文件的相对路径,或npm模块名,或npm模块路径。不支持绝对路径

作者:Hang Shao

出处:https://www.cnblogs.com/pam-sh/p/12310026.html

版权:本作品采用「知识共享」许可协议进行许可。

声明:欢迎交流! 原文链接 ,如有问题,可邮件(mir_soh@163.com)咨询.

posted @   PamShao  阅读(7114)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu