亲宝软件园·资讯

展开

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

换日线° 人气:0

本文着重给大家讲解了关于利用微信小程序获取当前时间及星期几的相关资料,文中通过代码实例讲解的非常细致,对大家的工作和学习具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

效果图如下所示

实例代码如下:

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

总结

加载全部内容

相关教程
猜你喜欢
用户评论