?一、直接使用方式
在小程序中獲取當前系統(tǒng)日期和時間,可直接拿來使用的常用的日期格式
//1. 當前日期 ?YYYY-MM-DD
new Date().toISOString().substring(0, 10)
new Date().toJSON().substring(0, 10)
//2. 當前日期 ?YYYY/MM/DD
new Date().toLocaleDateString()
//3. 當前時間? HH:mm:ss ? ?
new Date().toTimeString().substring(0,8)
?
?//4. 當前日期時間 ?YYYY-MM-DD HH:mm:ss ? ?
new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8)
二、封裝utils方式
2.1 utils代碼
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
}
//此處聲明幾個方法就寫幾個,如上面定義了formatTime 寫法如下
module.exports = {
formatTime: formatTime
}
一般放入utils工具類
2.2 utils調用?
? ?參考代碼
// 在需要使用的js文件中,導入js
var util = require('../../utils/util.js');
Page({
? data: {
?
? },
? onLoad: function () {
? ? // 調用函數(shù)時,傳入new Date()參數(shù),返回值是日期和時間
? ? let time = util.formatTime(new Date());
? ? // 再通過setData更改Page()里面的data,動態(tài)更新頁面的數(shù)據(jù)
? ? this.setData({
? ? ? time: time
? ? });
? }
?
})
?示例文章來源:http://www.zghlxwxcb.cn/news/detail-733749.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-733749.html
到了這里,關于微信小程序獲取當前日期時間的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!