Create a simple vue time filtering method

When using vue to display the time, it is often necessary to process and display the acquired time data. Here you can use the filters method to do so

For example: It is necessary to display the obtained time and compare it with the current time, display today, yesterday, and the day before, and the time earlier can be displayed as the required time format

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			#timeFilter li{
				list-style: none;
				margin: 5px 0px;
				background-color: ghostwhite;
			}
			#timeFilter li:nth-child(2n){
				background-color: gold;
			}
		</style>
		<title></title>
	</head>
	<body>
		<div id="timeFilter">
			<div>现在时间:{
   
   { nowtime }} </div>
			<ul>
				<li v-for="(item,index) in timeArr">这一次的时间是:{
   
   { item.start }} --- {
   
   { item.start | dateFormat01 }}</li>
			</ul>
		</div>
		<script type="text/javascript">
			var timeFilter = new Vue({
				el: "#timeFilter",
				data: {
					timeArr: [{
							start: '2017-8-9 11:12:15'
						}, {
							start: '2020-9-20 23:10:10'
						},
						{
							start: '2020-3-15 07:04:12'
						}, {
							start: '2020-9-19 04:50:12'
						},
						{
							start: '2020-9-21 17:10:01'
						}, {
							start: '2019-10-1 01:01:01'
						}
					],
					nowtime:new Date()
				},
				methods: {},
				filters: {
					dateFormat01: function(str) {
						var datestr = str.replace(/-/g, "/").replace(/T/g, " ");
						// 发布时间
						var dt = new Date(datestr);
						// 当前时间
						var dl = new Date();
						var dly = dl.getFullYear();
						var dlm = dl.getMonth();
						var dld = dl.getDate();
						// 获取当天零点的时间
						var zerodl = new Date(dly, dlm, dld, 0, 0, 0);
						var dateInterval1 = (dl - dt) / 1000 / 60 / 60 / 24;

						//判断发布时间与现在时间
						// 如果在同一天
						if (dt.getDate() == dld && dateInterval1 < 1) {
							var showday1 = "今天";
						} else {
							var dateInterval2 = (zerodl - dt) / 1000 / 60 / 60 / 24;

							if (dateInterval2 <= 1) {
								var showday1 = "昨天";
							} else if (dateInterval2 > 1 && dateInterval2 <= 2) {
								var showday1 = "前天";
							} else {
								var showday1 = dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
							}
						}
						var fn = function(str) {
							if (str < 10) {
								str = "0" + str;
								return str
							} else {
								return str
							}
						}
						return showday1 + " " + fn(dt.getHours()) + ":" + fn(dt.getMinutes());
					}
				}
			})
		</script>
	</body>
</html>

 

Guess you like

Origin blog.csdn.net/qq_36171287/article/details/108719605