微信小程序—顯示當前時間


問題

  在頁面上顯示當前時間(日期)

方法

  1、在util.js (創建項目自動生成)中:

   // 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顯示時間

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

  3、index.js中寫邏輯

 // 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模塊路徑。不支持絕對路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM