微信小程序获取系统日期和时间及时间戳

1.获取当前系统日期和时间

在小程序中,新建项目时,就会有一个utils.js文件,就是获取日期和时间的,代码如下:
在这里插入图片描述
utils.js:

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
 
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
 
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
 
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
 
module.exports = {
  formatTime: formatTime
}

使用示例:

index.js:

// 在需要使用的js文件中,导入js
var util = require('../../utils/util.js');
Page({
  data: {
 
  },
  onLoad: function () {
    // 调用函数时,传入new Date()参数,返回值是日期和时间
    var time = util.formatTime(new Date());
    // 再通过setData更改Page()里面的data,动态更新页面的数据
    this.setData({
      time: time
    });
  }
 
})

最后显示时间
index.wxml:

<view>{{time}}</view>

//或者
var sjc = 1488481383;
console.log(time.formatTime(sjc,'Y/M/D h:m:s'));
console.log(time.formatTime(sjc, 'h:m'));

2.获取时间戳

new Date('2018-09-03 15:46:13').getTime()

这个打印结果应该是时间戳,但是部分机型会返回 undefined 或者 Invalid date;
解决方法:

console.log(new Date('2018-09-03 15:46:13'
.replace(/-/g,"/")))

意思是把 2018-09-03 15:46:13 改为 2018/09/03 15:46:13

最后:

console.log(new Date('2018-09-03 15:46:13'
.replace(/-/g,"/")).getTime())

本篇文章提供的是基础逻辑,大家可根据自己的实际需要进行修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程思扬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值