当前位置:首页 >> 网络编程

微信小程序获取当前时间及星期几的实例代码

效果图如下所示

微信小程序获取当前时间及星期几的实例代码

实例代码如下:

util.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] "htmlcode">
const util = require('../../utils/util.js')
Page({
 data: {
 },
 onLoad: function (options) {

 let time = util.formatTime(new Date());

 console.log('当前日期和时间:', time)
	
	console.log('今天周几:', util.getWeekByDate(new Date()))
 
 //获取当前时间戳 
 var timestamp = Date.parse(new Date());
 timestamp = timestamp / 1000;
 
 console.log("当前时间戳为:" + timestamp);

 console.log("时间戳转日期:",util.formatTimeTwo(timestamp, 'Y-M-D h:m:s'));

 //获取当前时间 
 var n = timestamp * 1000;
 var date = new Date(n);
 //年 
 var Y = date.getFullYear();
 //月 
 var M = (date.getMonth() + 1 < 10 "当前日期和时间:" + Y + '-' + M + '-' + D + ' ' + h + ":" + m + ":" + s);
 },
})

参考手册:https://www.w3school.com.cn/js/js_date_methods.asp

总结