DEV Community

Olufemi Oyedepo
Olufemi Oyedepo

Posted on

6 1

Datetime Filter in Vue 3 using Moment.js

Datetime Filter in Vue 3 using Moment.js

It turns out that Filters have been removed 😏 in Vue 3 Official docs link.

So that practically makes it a bit hard to format date/datetime in Vue 3. According to the official docs, the use of global filters is now encouraged but in my opinion, I'm not too sure the use of global filters would solve the problem at hand.

So, I looked around but couldn't find much examples but I was able to eventually come up with something with the help of this famous library [Moment.js] πŸ•— (https://momentjs.com/)

Let's dive straight into it.

  1. Install moment js from npm npm install moment --save
  2. In your component
import moment from 'moment'
export default {
...
  created: function () {
    this.moment = moment;
  },
  setup() {
   let todaysDate = new Date();
  }
...
}

<div>
   {{ moment(todaysDate).format("ddd MMM DD, YYYY [at] HH:mm a") }}
   <!-- As of the time of writing, this gives ==> Thu May 13, 2021 at 19:42 pm -->
</div>
Enter fullscreen mode Exit fullscreen mode

So that's it πŸ˜‰. Please feel free to change the format to suit your use case.
Suggestions/comments are welcome. Thanks πŸ™ πŸ™ πŸ™

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (3)

Collapse
 
allanneves profile image
Allan Neves β€’ β€’ Edited

Thank you! If you don't mind the question, why do we need to assign the moment to itself upon creation in the life cycle? Obviously, we cannot use it as a component but I don't understand the black magic behind it.

Collapse
 
blazejplis profile image
Blazej Plis β€’

Thank you for that!

Collapse
 
olufemi_oyedepo profile image
Olufemi Oyedepo β€’

You're most welcome 😎

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more