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

时间:2021-05-18

效果图如下所示

实例代码如下:

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://.cn/js/js_date_methods.asp

总结

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章