2

I'm receiving dates from my database in the format 2018-08-08 15:38:48 however I want it to show 3:38 pm instead.

I'm just unsure when to make this change, can I change it while it is being posted? They are dates of messages being sent to a person.

Current code:

<div v-for="messages in userMessages">
   <div class="date">
       {{ user.created_at }}
   </div>
</div>

Output:

2018-08-08 15:38:48

How do I transform the date in vue? (when it is in a v-for?)

ESP32
  • 8,089
  • 2
  • 40
  • 61
Otto
  • 663
  • 3
  • 17
  • 33
  • 1
    [This question](https://stackoverflow.com/q/49619999/8913537) gives you a glimpse on how you can format date strings using JavaScript in vue. It is not your usecase, but you could start here. – Philipp Maurer Aug 10 '18 at 13:45

4 Answers4

2

Vue does not offer date formatting. You will need your own filter to format the date. Or you use a package like the following: https://github.com/brockpetrie/vue-moment#readme

<span>{{ someDate | moment("hh:mm a") }}</span>
ESP32
  • 8,089
  • 2
  • 40
  • 61
1

Vue.js does not natively allow dates to be formatted in a different way.

I suggest you to use more famous libraries like moment.js to format your dates however you want.

For example:

import moment from 'moment'

Vue.filter('formatDate', function(value) {
  if (value) {
    return moment(String(value)).format('MM/DD/YYYY hh:mm')
  }
}
GiamPy
  • 3,543
  • 3
  • 30
  • 51
1

https://momentjs.com/

How do you use it?

You can use like this.

moment('2018-08-08 15:38:48').format('LTS'); // 03:38:48 PM
kyun
  • 9,710
  • 9
  • 31
  • 66
0

Your datetime format is not the ISO standard we would like, but we'll live with it... When handling dates, it's a good practice to convert them to date objects as soon as you receive them. If they're arriving in JSON, you can do this with a reviver function as the second argument to JSON.parse(). Here is a reviver function that will do the job for you...

Then,at the point you need to display, you can format your time with toLocaleTimeString()

function nReviver(key, value) {
        var a;
        if (typeof value === "string") {
            a = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d*)?$/.exec(value);
            if (a) {
                return new Date(a[0]);
            }
        }
        return value;
    }
    
    // do this when you receive your data from the server and all
    // dates, wherever they are in the JSON, will be converted to date objects
    var myObj = JSON.parse('{"myDate":"2018-08-08 15:38:48"}',nReviver)

    // ...then, when you want to display, format with toLocaleTimeString()
    console.log(
      myObj.myDate.toLocaleTimeString({},{
        hour12:true,
        hour:'numeric',
        minute:'numeric'
      })
      .toLowerCase()
    )
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110