js判断时间是否为当天(今天是今天)

场景:在某些时候,某些项目需要做发送默认消息,默认消息一天只发送一次,当天时间为当天零点到当天的二十三时五十九分五十九秒,然后当时间切换到第二天时,只要用户是第二天第一打开就发送默认消息,如果之后再次打开,就不发送了。

思路:获取当前进入该窗口的时间转换为当时的时间存于缓存中,以后每次进入该页面,获取进入的时间和缓存时间进行对比,如果相同则不发送默认消息,如果不同则把缓存中的时间更新为当前进入的换算好的时间同时发送默认消息即可。

当然了,第一次进入是取不到值的,此时就需要判断若缓存中该键对应的值不存在 (为空,undefined)时,就把当日的时间赋给缓存并发送默认消息即可。

1.代码实现

1.1主要代码:

<html>

	<head>
		<title></title>
		<style type="text/css">

		</style>
	</head>

	<body>
		<script type="text/javascript">
			var old_time = '20190123235959';
			var now_time = get_endtime();
			var compare_res = compare_time(old_time)
			console.log(" old_time: "+old_time," now_time:"+now_time," 是否为同一天: "+compare_res);
			
			// 比较时间是否为当天
			function compare_time(time) {
			  var today_end = get_endtime();
			  var time_old = time;
			  if (today_end == time_old) {
			    return 1
			  } else {
			    return 0
			  }
			}
			
			// 获取当日23:59:59时间
			function get_endtime() {
			  var time_end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
			  var time_format = format_date(time_end)
			  return time_format;
			}
			
			// 获取当前时间的  年月日时分秒  的时间格式化 20191220100246
			function format_date(now) {
			  var year = now.getFullYear(); //年
			  var month = now.getMonth() + 1; //月
			  var day = now.getDate(); //日
			  var hh = now.getHours(); //时
			  var mm = now.getMinutes(); //分
			  var ss = now.getSeconds(); //秒
			
			  var clock = year + "";
			  if (month < 10) {
			    clock += "0";
			  }
			  clock += month + "";
			
			  if (day < 10) {
			    clock += "0";
			  }
			  clock += day + "";
			
			  if (hh < 10) {
			    clock += "0";
			  }
			  clock += hh + "";
			
			  if (mm < 10) {
			    clock += '0'
			  }
			  clock += mm;
			
			  if (ss < 10) {
			    clock += '0'
			  }
			  clock += ss;
			
			  return clock;
			}
		</script>
	</body>

</html>

1.2 结果

猜你喜欢

转载自blog.csdn.net/hangGe0111/article/details/103667553