效果图如下所示
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('7', '1', '2', '3', '4', '5', '6');
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
对你有帮助的话记得收藏点赞,有什么问题欢迎评论留言。