小程序调用JS的方法

Util.js工具类代码

注意:"=>" 前面的是参数
如下方 getDay 是方法名, day 是传入的参数,返回的是一个拼接的字符串 tYear + "-" + tMonth + "-" + tDate

require('../app.js')
/**
 * 获取时间
 * day --> 和今天相差多少天 -2(前天) -1(昨天) 0(今天) 1(明天) 2(后天) 3(大后天)...
 */
const getDay = day => {
  var today = new Date();

  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;

  today.setTime(targetday_milliseconds); //注意,这行是关键代码

  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear + "-" + tMonth + "-" + tDate;
}

/**
 * 格式化时间,传入一个js的Date: new Date()
 */
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(':')
}

//给外界调用
module.exports = {
  formatTime: formatTime,
  getDay: getDay,
}

注意:
const formatTime = date => {
date 是js的Date,在外部调用时需要使用JS创建Date的方法:new Date(),而不是使用小程序的方法创建Date()

var util = require('../../utils/util.js')
Page({
   /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
      var that = this;
      let date = util.formatTime(new Date()); 
    }
})

你可能感兴趣的:(小程序调用JS的方法)