微信小程序获取当前时间方法
时间: 2023-10-10 14:07:59 浏览: 119
可以使用 JavaScript 的 Date 对象来获取当前时间。具体实现方法如下:
1. 在小程序中创建一个 js 文件,例如 utils.js。
2. 在 utils.js 中编写以下代码:
```
function getCurrentTime() {
const date = new 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}-${addZero(month)}-${addZero(day)} ${addZero(hour)}:${addZero(minute)}:${addZero(second)}`;
}
function addZero(num) {
return num < 10 ? `0${num}` : num;
}
module.exports = {
getCurrentTime
};
```
3. 在需要获取当前时间的页面或组件中引入 utils.js,并调用 getCurrentTime 方法即可。
示例代码:
```
const utils = require('../../utils.js');
Page({
data: {
currentTime: ''
},
onLoad: function () {
const currentTime = utils.getCurrentTime();
this.setData({
currentTime
});
}
});
```
这样就可以在页面中显示当前时间了。
阅读全文
相关推荐


















