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



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

转自:http://blog.csdn.net/michael_ouyang/article/details/55189331

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

utils.js:

 

[javascript] view plain copy

  1. function formatTime(date) {
  2.   var year = date.getFullYear()
  3.   var month = date.getMonth() + 1
  4.   var day = date.getDate()
  5.   var hour = date.getHours()
  6.   var minute = date.getMinutes()
  7.   var second = date.getSeconds()
  8.   return [year, month, day].map(formatNumber).join(‘/’) + ’ ’ + [hour, minute, second].map(formatNumber).join(‘:’)
  9. }
  10. function formatNumber(n) {
  11.   n = n.toString()
  12.   return n[1] ? n : ’0′ + n
  13. }
  14. module.exports = {
  15.   formatTime: formatTime
  16. }

 

使用示例:

index.js:


 

[javascript] view plain copy

  1. // 在需要使用的js文件中,导入js
  2. var util = require(‘../../utils/util.js’);
  3. Page({
  4.   data: {
  5.   },
  6.   onLoad: function () {
  7.     // 调用函数时,传入new Date()参数,返回值是日期和时间
  8.     var time = util.formatTime(new Date());
  9.     // 再通过setData更改Page()里面的data,动态更新页面的数据
  10.     this.setData({
  11.       time: time
  12.     });
  13.   }
  14. })

 

 

index.wxml:

[html] view plain copy

  1. <view>{{time}}</view>

运行结果: