How to convert date from string datetype in Vue and Pug?

Viewed 107

I have this pug file which I want to compare the system date with the date in the object using VueJs.

This is what I have. I have print the system date using this line div #{new Date()} which output Mon Oct 18 2021 10:46:39 GMT+0800 (Malaysia Time)

I have also print the date using this vue syntax div {{event.details.meta.date}} which output 2021-10-17

The question is how do I convert this date from string to datatype and then compare it to the system date?

I tried with div #{new Date("event.details.meta.date")} but the output is Invalid date

I tried div(v-if="isEventActive(event.details.meta.date)")

and

computed: {
  isEventActive(_eventDate) {
    var eventDate = new Date(_eventDate);
    return new Date() < eventDate;
  }, 
}

But it says isEventActive is not a function

2 Answers

div #{new Date("event.details.meta.date")} outputs Invalid date because the string "event.details.meta.date" is not a valid value for the Date() constructor.

div #{new Date(event.details.meta.date)} on the other hand should output something like Mon Oct 17 2021 08:00:00 GMT+0800 (Malaysia Time) because you are passing the value of event.details.meta.date, which apparently is '2021-10-17', to the Date() constructor.


div(v-if="isEventActive(event.details.meta.date)") outputs <div v-if="isEventActive(event.details.meta.date)"></div>.

You probably want this instead: <div v-if="isEventActive('2021-10-17')"></div>. Then in your isEventActive method the value of the _eventDate parameter would be '2021-10-17'. (Probably; I'm not familiar with Vue.)

So you could try this:

// Input (Vue):
div(v-if=`isEventActive('${event.details.meta.date}')`)

// Output (HTML):
<div v-if="isEventActive('2021-10-17')"></div>

The same but without a template literal:

// Input (Vue):
div(v-if="isEventActive('" + event.details.meta.date + "')")

// Output (HTML):
<div v-if="isEventActive('2021-10-17')"></div>

Vue computed properties don't accept parameters. It's the return value of the function that is visible in your template.

To solve your issue, you can either:

  1. move your isEventActive function into the methods section, or
  2. use a computed property and return a function.

The first approach looks like this:

methods: {
    isEventActive(_eventDate) {
        var eventDate = new Date(_eventDate);
        return new Date() < eventDate;
    }, 
}

If this doesn't work (i.e., the page doesn't properly update on changes to eventDate) then try this:

computed: {
    isEventActive() {
        return function(_eventDate) {
            var eventDate = new Date(_eventDate);
            return new Date() < eventDate;  
        }
    }
}
Related