微信小程序封装函数总集之二:获取系统时间

函数二:获取系统时间

背景:如果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:一般时间如果要比较大小,依次比较年月日,时分秒非常的慢。一般会转换到时间戳进行大小比较。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值