SoFunction
Updated on 2025-04-05

In vue, the corresponding time is determined based on the timestamp (Today, yesterday, the day before yesterday)

Display the corresponding time period according to the timestamp

This article is based on vue abbreviation, but the principles are all figured out.

According to a timestamp, the corresponding time period is then displayed. If it is today, the corresponding time is displayed. If it is yesterday, it is yesterday, and if it is the day before yesterday, it is the day before yesterday. The remaining ones are displayed as the corresponding date

The requirements are defined, and then the implementation begins:

First, it is to convert the timestamp to the corresponding time format. JS provides a native method to obtain the corresponding year, month, day and other formats, but it is not flexible enough. Here is a function that is more flexible to obtain fixed formats found online.

const formatDate = (date, fmt) => {
 date = new Date(date);
 if (typeof (fmt) === "undefined") {
  fmt = "yyyy-MM-dd HH:mm:ss";
 }
 if (/(y+)/.test(fmt)) {
  fmt = (RegExp.$1, (() + '').substr(4 - RegExp.$))
 }
 let o = {
  'Y': (),
  'M+': () + 1,
  'd+': (),
  'H+': (),
  'm+': (),
  's+': ()
 }
 for (let k in o) {
  if (new RegExp(`(${k})`).test(fmt)) {
   let str = o[k] + ''
   fmt = (RegExp.$1, RegExp.$ === 1 ? str : ('00' + str).substr());
  }
 }
 return fmt
}

Using this function, you need to provide a timestamp and a date format.

// `+new Date()` is abbreviation for obtaining the current timestamp// `yyyy-MM-dd HH:mm:ss` is the date format you want to obtainformatDate(+new Date(), 'yyyy-MM-dd HH:mm:ss') // 2019-12-18 20:29:31

Next is to use filters to filter timestamps. vue provides filters that can define global filters and local filters. We define a local filter

// 
// Use modularity here to define the filter function in the external js fileconst formatDate ......

export { formatDate }

// 
import { formatDate } from 'common'

export default {
 data () {
 return {
  time: 1576673222857
 }
 },
 methods: {},
 created() {},
 filters: {
 formateDate(data, fmt) {
  return formatDate(data, fmt)
 }
 }
}

After defining the filter, it can be used in the page

//

<template>
 <div>
 <span>{{ time | formateDate('MM-dd') }}</span>
 </div>
</template>

Use the | (pipe character) to filter the timestamp. The first parameter of the filter is on the left side of the pipe character, and the second parameter is the filter format. After the definition is made, the corresponding time format will be displayed according to the format.

The next last step is to compare today's date to display the corresponding time (yesterday, day before yesterday)
Here, use vue's if else to determine which date format should be displayed.

&lt;template&gt;
 &lt;div&gt;
 &lt;span v-if="new Date(time).getDate() === new Date().getDate()"&gt;{{ time | formateDate('HH:mm') }}&lt;/span&gt; 
 // Here we convert the timestamp to `day`, and then compare it with the current `day`. If it is equal, it means it is today's timestamp, and `time` is displayed &lt;span v-else-if="new Date(time).getDate() === (new Date().getDate() - 1)"&gt;{{ time | formateDate('HH:mm') }}&lt;/span&gt; 
  // Here we put the time stamp of **current** `-1`, which means it was yesterday.  For example, today is the 18th, and after `-1` it is 17. If the `time` is equal to 17 after conversion, the instructions should be displayed as `Yesterday`.  &lt;span v-else-if="new Date(time).getDate() === (new Date().getDate() - 2)"&gt;{{ time | formateDate('HH:mm') }}&lt;/span&gt; 
  // `-2` is `The day before yesterday`  &lt;span v-else&gt;{{ time | formateDate('MM-dd') }&lt;/span&gt;
  // Otherwise it will be displayed as the corresponding date &lt;/div&gt; 
&lt;/template&gt;

OK, the above is to compare the corresponding time according to the date. ——But, do you think it's over?

An important question is that there are one of the 30 days of each month. Today is December 18, which is equal to 18, showing the corresponding time, but what if it is November 18? It is obviously wrong if the corresponding time is also displayed.

Therefore, the year, month and day should be compared, and then the corresponding time should be determined.

So the code should be as follows:

 &lt;span class="lastDate"
  v-if="(new Date(time).getDate() == new Date().getDate()) &amp;&amp; (new Date().getMonth() == new Date().getMonth()) &amp;&amp; (new Date().getYear() == new Date().getYear())"
   &gt;{{time | FormatDate( 'HH:mm')}}&lt;/span&gt;
   
 &lt;span class="lastDate"
  v-if="(new Date(time).getDate() == new Date().getDate() - 1) &amp;&amp; (new Date().getMonth() == new Date().getMonth()) &amp;&amp; (new Date().getYear() == new Date().getYear())"
   &gt;yesterday&lt;/span&gt;

 &lt;span class="lastDate"
  v-if="(new Date(time).getDate() == new Date().getDate() - 1) &amp;&amp; (new Date().getMonth() == new Date().getMonth()) &amp;&amp; (new Date().getYear() == new Date().getYear())"
   &gt;The day before yesterday&lt;/span&gt;
   
 &lt;span v-else&gt;{{ time | formateDate('MM-dd') }&lt;/span&gt;

Although it is completed to compare the year, month and date, the corresponding date will be displayed. But looking at these codes, it is extremely ugly and difficult to understand, so we should not write so much judgment code in html, so, let's encapsulate it into a function, and then use function comparison.

Before encapsulating the function, let’s first determine what are the same and different in the above judgment codes.

The same is

  • Use new Date(time) to compare new Date()
  • Use getDate()/getMonth()/getYear()
  • Use two && to compare

The difference is

  • A new Date() requires parameter time, and the other does not require parameter

Some need - corresponding numbers

I roughly sorted out the above parts, wrote the same into the function, and used different formal parameters, that is, arguments.

//

const compareDate = (timestamp, day = 0) =&gt; {
 // timestamp is the timestamp to be passed in // day is the day to be subtracted. Because if you compare the *day*, you do not need to subtract it, so it is defined as 0 by default. 
 // According to the above analysis, some require the parameter `time`, and some do not, so use a function to distinguish it. let newDate = (time = null) =&gt; {
 return time === null ? new Date() : new Date(time)
 }
 
 // Return the value after comparison here. If the value after success, it will return `true`, and if it fails, it will return `false` return (newDate(timestamp).getDate() == newDate().getDate() - day) &amp;&amp; (newDate(timestamp).getMonth() == newDate().getMonth()) &amp;&amp; (newDate(timestamp).getYear() == newDate().getYear()) 
}

export {
 compareDate
}

The above is the encapsulated function, but there is a problem, that is, the function has written the year, month and day, because there are currently three, so let’s start with this. If you have time, you can change to distinguish the year, month or day according to the parameters.

Then you can use it. You need to pay attention when using it. I have already said it in this blog, so I won’t go into details here. Just put the code:

// 
import { compareDate } from ''
data() {
 return {
 compare: compareDate
 }
}
&lt;template&gt;
 &lt;div&gt;
  &lt;span v-if="compare(time)"&gt;{{time | FormatDate( 'HH:mm')}}&lt;/span&gt;
  &lt;span v-else-if="compare(time, 1)"&gt;yesterday&lt;/span&gt;
  &lt;span v-else-if="compare(time, 2)"&gt;The day before yesterday&lt;/span&gt;
   &lt;span v-else&gt;{{time | FormatDate( 'MM-d')}}&lt;/span&gt;
 &lt;/div&gt; 
&lt;/template&gt;

Isn’t this much simpler? , and it is easy to understand and clear to look.

The above is to compare the corresponding date displayed according to the time stamp. If there is a better way, please feel free to discuss it. If you have any questions, you can also leave a message.

Summarize

The above is the time stamp in vue introduced by the editor to determine the corresponding time (today, yesterday, the day before yesterday). I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!