函数二:获取系统时间
背景:如果rd只给你返回了开始时间或者结束时间,要计算与当前时间的状态。则经常需要获取得到当前的系统时间。
微信小程序中,在utils中自带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, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime
}
index.js
var util = require('../../utils/util.js')
Page({
data:{
time : '2018-07-26 15:22:04',
systemTime : ''
},
// 点我倒计时开始
countdown:function(){
console.log(this.data.time)
},
onLoad:function(){
console.log(new Date())
// 打印出来:Mon Aug 27 2018 19:25:09 GMT+0800 (CST)
// 调用函数时,传入new Date()参数,返回值是日期和时间
var systemTime = util.formatTime(new Date());
// 再通过setData更改Page()里面的data,动态更新页面的数据
this.setData({
systemTime: systemTime
})
}
})
console.log(new Date())
打印出来:Mon Aug 27 2018 19:25:09 GMT+0800 (CST)
index.wxml
<wxs src="./index.wxs" module="util"></wxs>
<view>这里是首页</view>
<view bindtap="countdown">点我倒计时开始</view>
<view>{{util.formatstartTime(time)}}开抢</view>
<view>系统时间:{{systemTime}}</view>
微信小程序展示页
ps:一般时间如果要比较大小,依次比较年月日,时分秒非常的慢。一般会转换到时间戳进行大小比较。