好久没写笔记了,今天简单的记录下在开发小程序时,遇到了页面获取当前时间和时间段,记录总结以下。
首先我们在utils文件 中新建一个js文件,然后把当前时间和时间段的代码写在这个文件中。代码就如下:
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
return year + "年" + month + "月" + day + "日";
}
const formatDay = dates => {
let _day = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
let date = new Date(dates);
date.setDate(date.getDate());
let day = date.getDay();
return _day[day];
}
const formatSole = () => {
let timeNow = new Date();
let hours = timeNow.getHours();
let text = ``;
if (hours >= 0 && hours <= 6) {
text = `深夜了,不要熬夜太久哟`;
} else if (hours > 6 && hours <= 8) {
text = `早上好`;
} else if (hours > 8 && hours <= 10) {
text = `上午好`;
} else if (hours > 10 && hours <= 13) {
text = `中午好`;
} else if (hours > 13 && hours <= 17) {
text = `下午好`;
} else if (hours > 17 && hours <= 23) {
text = `晚上好`;
}
return text;
}
module.exports = {
formatTime: formatTime,
formatDay: formatDay,
formatSole: formatSole
}
然后再项目页面中的js文件引入该js文件,我的需求是页面加载后显示,代码如下:
var util = require('../../utils/time.js')
Page({
data: {
promptTime:'',
promptDay:'',
promptTimeSole:'',
},
onLoad: function(options) {
this.setData({
promptTime: util.formatTime(new Date()),
promptDay: util.formatDay(new Date()),
promptTimeSole: util.formatSole(),
});
},
})
这样就能实现在页面中显示当前年-月-日-周 时间段了。效果图如下: