uni-app:实现当前时间的获取,并且根据当前时间判断所在时间段为早上,下午还是晚上

效果图

核心代码

获取当前时间

**toString()**方法将数字转换为字符串

padStart(2, '0'):padStart()方法用于在字符串头部填充指定的字符,使其达到指定的长度。该方法接受两个参数:第一个参数为期望得到的字符串长度,第二个参数为要填充的字符。

javascript 复制代码
// 获取当前时间
const now = new Date();
// 获取当前日期
var year = now.getFullYear();
var month = (now.getMonth() + 1).toString().padStart(2, '0');
var day = now.getDate().toString().padStart(2, '0');
// 获取当前详细时间
var hours = now.getHours().toString().padStart(2, '0');
var minutes = now.getMinutes().toString().padStart(2, '0');
var seconds = now.getSeconds().toString().padStart(2, '0');
// 拼接日期和时间
var datetime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;

时间段的判断

根据小时来判断当前的时间段,这里规定早上:6:00-12:00,下午:12:00-18:00,其余时间为晚上

javascript 复制代码
const startTime = 6; // 早上开始时间(小时)
const noonTime = 12; // 下午开始时间(小时)
const endTime = 18; // 晚上开始时间(小时)
// 判断当前时间所属时间段,并输出相应的问候语
var tp = '';
// 早上6-12
if (hours >= startTime && hours < noonTime) {
	tp = '早上好';
//下午12-18
} else if (hours >= noonTime && hours < endTime) {
	tp = '下午好';
//晚上
} else {
	tp = '晚上好';
} 

完整代码

html 复制代码
<template>
	<view>
		{{tp+',当前时间为:'+datetime}}
	</view>
</template>
<script>
	export default {
		data() {
			return {
				tp:'',//当前时间段
				datetime:'',//当前时间
			}
		},
		methods: {

		},
		onLoad() {
			// 获取当前时间
			const now = new Date();
			// 设置时间段划分的时间点,规定早上:6:00-12:00,下午:12:00-18:00,其余时间设置为晚上
			const startTime = 6; // 早上开始时间(小时)
			const noonTime = 12; // 下午开始时间(小时)
			const endTime = 18; // 晚上开始时间(小时)
			var tp = '';
			// 获取当前日期
			var year = now.getFullYear();
			var month = (now.getMonth() + 1).toString().padStart(2, '0');
			var day = now.getDate().toString().padStart(2, '0');
			// 获取当前时间
			var hours = now.getHours().toString().padStart(2, '0');
			var minutes = now.getMinutes().toString().padStart(2, '0');
			var seconds = now.getSeconds().toString().padStart(2, '0');
			// 拼接日期和时间
			var datetime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
			// 判断当前时间所属时间段,并输出相应的问候语
			// 早上6-12
			if (hours >= startTime && hours < noonTime) {
				tp = '早上好';
				//下午12-18
			} else if (hours >= noonTime && hours < endTime) {
				tp = '下午好';
				//晚上
			} else {
				tp = '晚上好';
			} 
			//将数据存入data中
			this.tp = tp;
			this.datetime = datetime
		}
	};
</script>
<style>

</style>
相关推荐
借个火er1 天前
Vue.js 源码揭秘(一):Vue3 架构总览
前端
千寻girling1 天前
面试官: “ 请你说一下什么是 ajax ? ”
前端·javascript
MQliferecord1 天前
webpack的生命周期与Loader/Plugin
前端
@大迁世界1 天前
JavaScript 框架的终结
开发语言·前端·javascript·ecmascript
PPPPickup1 天前
easychat项目复盘---管理端系统设置
java·开发语言·前端
梦6501 天前
Vue 实现动态路由
前端·javascript·vue.js
姜糖编程日记1 天前
C++——初识(2)
开发语言·前端·c++
丶乘风破浪丶1 天前
Vue项目中判断相同请求的实现方案:从原理到实战
前端·javascript·vue.js
why技术1 天前
如果让我站在科技从业者的角度去回看 2025 年,让我选一个词出来形容它,我会选择“vibe coding”这个词。
前端·后端·程序员
毕设源码-郭学长1 天前
【开题答辩全过程】以 基于uni-app的维修上门服务小程序设计与实现为例,包含答辩的问题和答案
uni-app