skip to Main Content

i want show unique date in message chat
Example.

data() {
 return {
  message: [
    {id: 1,message: 'hi', created_at: '2023-02-16 00:44:41'},
    {id: 2,message: 'how are you?', created_at: '2023-02-16 01:00:00'},
    {id: 3,message: 'hello', created_at: '2023-03-01 12:00:00'},
    {id: 5,message: 'hi', created_at: '2023-03-01 15:56:00'},
  ]
 }}

example result date in message
enter image description here

2

Answers


  1. You should format the date property.
    You can create a function:

    formattedDate(date) {
      const dateObj = new Date(date)
      return dateObj.toLocaleDateString('en-US')
    }
    

    Then in your template when calling the date prop, you can send it as function property. For example:

    <ul>
    <li v-for="message in messages" :key="message.id">
    {{ formattedDate(message.created_at) }}
    </li>
    </ul>
    
    Login or Signup to reply.
  2. You have to create an additional prop for your messages array, for example "show_date". This prop will determine whether to show the date or not.

    You can do it by computed value:

    computed: {
      messages() {
        return this.message.map((m, index) => {
          // Get previous message from source array
          const prevMessage = this.message[index - 1];
          if (prevMessage) { // If previous message exists let's check the dates
            return {...m, show_date: !this.isSameDate(m.created_at, prevMessage.created_at) };
          } else { // otherwise we will show the date
            return {...m, show_date: true };
          }
        });
      },
    },
    

    Here is the func for check if dates are the same day, but you can use momentjs or dayjs instead

    methods: {
      isSameDate(first, second) {
        const firstDate = new Date(first);
        const secondDate = new Date(second);
        return firstDate.getFullYear() === secondDate.getFullYear() && 
          firstDate.getMonth() === secondDate.getMonth() && 
          firstDate.getDate() === secondDate.getDate();
      },
    },
    

    And finally, you have to render messages by the computed prop and display date only if ‘show_date’ is true.

    <div v-for="m in messages" :key="m.id">
      <div v-if="m.show_date">
        {{ m.created_at }}
      </div>
      <div>
        {{ m.message }}
      </div>
    </div>
    

    You can find full code here: https://codepen.io/AlekseiKrivo/pen/xxyXpmY

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search