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

效果图如下所示

实例代码如下:

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] ? n : "0" + n
}
function formatTimeTwo(number, format) {
 var formateArr = ["Y", "M", "D", "h", "m", "s"];
 var returnArr = [];
 var date = new Date(number * 1000);
 returnArr.push(date.getFullYear());
 returnArr.push(formatNumber(date.getMonth() + 1));
 returnArr.push(formatNumber(date.getDate()));
 returnArr.push(formatNumber(date.getHours()));
 returnArr.push(formatNumber(date.getMinutes()));
 returnArr.push(formatNumber(date.getSeconds()));
 for (var i in returnArr) {
 format = format.replace(formateArr[i], returnArr[i]);
 }
 return format;
}

const getWeekByDate = dates => {
 let show_day = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
 let date = new Date(dates);
 date.setDate(date.getDate());
 let day = date.getDay();
 return show_day[day];
}

module.exports = {
 formatTime: formatTime,
 formatTimeTwo: formatTimeTwo,
 getWeekByDate: getWeekByDate
}

.js

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 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);
 //日 
 var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
 //时 
 var h = date.getHours();
 //分 
 var m = date.getMinutes();
 //秒 
 var s = date.getSeconds();


 console.log("当前年月日:",date.toLocaleDateString());

 console.log("当前日期时间:",date.toLocaleString());

 console.log("当前时间:",date.toLocaleTimeString());

 console.log("当前日期和时间:" + Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s);
 },
})

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

总结

到此这篇关于微信小程序获取当前时间及星期几的文章就介绍到这了,更多相关微信小程序获取当前时间及星期几内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!

原文链接:https://blog.csdn.net/qq_43764578/article/details/106059340