uniapp开发 需要处理显示不同的时间格式 如下,这个要怎么处理?
您好,针对uniapp的日期格式展示需求,可以通过以下代码实现:
// 获取当前时间戳
var now = new Date().getTime()
// 时间差(单位:毫秒)
var diff = now - yourDate.getTime()
// 超过两天,按星期几展示
if (diff >= 172800000) {
var weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
return weekdays[yourDate.getDay()]
}
// 超过一天,显示昨天/今天
else if (diff >= 86400000) {
var yesterday = new Date(now - 86400000)
if (yourDate.getDate() === yesterday.getDate()) {
return '昨天 ' + format(yourDate, 'HH:mm')
} else {
return '今天 ' + format(yourDate, 'HH:mm')
}
}
// 不超过一天,按时-分展示
else {
return format(yourDate, 'HH:mm')
}
其中,format 函数是用于格式化具体时间的,具体实现方式可以自行编写。此处给出一个常见的实现方式:
function format(date, fmt) {
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"H+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
希望对您有所帮助
let timer = setInterval(() =>{this.settime()} ,1000)
settime(){
//获取当前时间
this.nowtime=new Date().toLocaleString()
},
可以使用JavaScript中的Date对象来获取不同的时间格式,并在页面上展示。具体步骤如下:
data() {
return {
currentDate: new Date()
}
}
mounted() {
setInterval(() => {
this.currentDate = new Date()
}, 1000)
}
<!-- 年月日 -->
{{ currentDate.getFullYear() }}年{{ currentDate.getMonth() + 1 }}月{{ currentDate.getDate() }}日
<!-- 小时分钟秒 -->
{{ currentDate.getHours() }}:{{ currentDate.getMinutes() }}:{{ currentDate.getSeconds() }}
完整代码如下:
<template>
<div>
<div>年月日:{{ currentDate.getFullYear() }}年{{ currentDate.getMonth() + 1 }}月{{ currentDate.getDate() }}日</div>
<div>小时分钟秒:{{ currentDate.getHours() }}:{{ currentDate.getMinutes() }}:{{ currentDate.getSeconds() }}</div>
</div>
</template>
<script>
export default {
data() {
return {
currentDate: new Date()
}
},
mounted() {
setInterval(() => {
this.currentDate = new Date()
}, 1000)
}
}
</script>
注意:在实际开发中,如果需要支持不同的时间格式,并且需要在多个页面中使用,建议将获取时间格式的逻辑封装成一个公共的函数,然后在需要使用的组件中引入并调用。这样可以避免代码重复,并方便后续的维护和修改。