Giter VIP home page Giter VIP logo

vue-moment's Introduction

vue-moment

npm version Build Status Monthly Downloads License: MIT

Handy Moment.js filters for your Vue.js project.

Installation

Install via NPM...

$ npm install vue-moment

...and require the plugin like so:

Vue.use(require('vue-moment'));

Typescript (optional)

If you project is using Typescript, you can add type infomation using a 3rd party lib

npm install @types/vue-moment --save-dev

Usage

Simply set moment as the filtering function and you're good to go. At least one argument is expected, which the filter assumes to be a format string if the argument doesn't match any of the other filtering methods.

<span>{{ someDate | moment("dddd, MMMM Do YYYY") }}</span>
<!-- or create a new date from 'now' -->
<span>{{ new Date() | moment("dddd, MMMM Do YYYY") }}</span>

Passing Your Date

Moment.js expects your input to be either: a valid ISO 8601 formatted string (see http://momentjs.com/docs/#/parsing/string/), a valid Date object, a Unix timestamp (in seconds or milliseconds, passed as a Number), or a date string with an accompanying format pattern (i.e. when you know the format of the date input). For the latter, vue-moment allows you to pass your date and format pattern(s) as an array, like such:

<span>{{ [ someDate, "MM.DD.YY" ] | moment("dddd, MMMM Do YYYY") }}</span>
<!-- or when you want to parse against more than one pattern -->
<span>{{ [ someDate, ["MM.DD.YY", "MM-DD-YY", "MM-DD-YYYY"] ] | moment("dddd, MMMM Do YYYY") }}</span>

As of 3.0.0, passing an empty or invalid input will no longer initiate moment with a new Date object fallback.

Filtering Methods

format (default)

This is the default filtering option. Formats the date against a string of tokens. See http://momentjs.com/docs/#/displaying/format/ for a list of tokens and examples.

Default

<span>{{ someDate | moment("YYYY") }}</span>
<!-- e.g. "2010" -->
<span>{{ someDate | moment("ddd, hA") }}</span>
<!-- e.g. "Sun, 3PM" -->
<span>{{ someDate | moment("dddd, MMMM Do YYYY, h:mm:ss a") }}</span>
<!-- e.g. "Sunday, February 14th 2010, 3:25:50 pm" -->

For more information about moment#format, check out http://momentjs.com/docs/#/displaying/format/.

from

Display a Moment in relative time, either from now or from a specified date.

Default (calculates from current time)

<span>{{ someDate | moment("from", "now") }}</span>
<!-- or shorthanded -->
<span>{{ someDate | moment("from") }}</span>

With a reference time given

<span>{{ someDate | moment("from", "Jan. 11th, 1985") }}</span>

With suffix hidden (e.g. '4 days ago' -> '4 days')

<span>{{ someDate | moment("from", "now", true) }}</span>
<!-- or -->
<span>{{ someDate | moment("from", true) }}</span>
<!-- or with a reference time -->
<span>{{ someDate | moment("from", "Jan. 11th, 2000", true) }}</span>

For more information about moment#fromNow and moment#from, check out http://momentjs.com/docs/#/displaying/fromnow/ and http://momentjs.com/docs/#/displaying/from/.

calendar

Formats a date with different strings depending on how close to a certain date (today by default) the date is. You can also pass a reference date and options.

Default (calculates from current time)

<span>{{ someDate | moment("calendar") }}</span>
<!-- e.g. "Last Monday 2:30 AM" -->

With a reference time given

<span>{{ someDate | moment("calendar", "July 10 2011") }}</span>
<!-- e.g. "7/10/2011" -->

With options

<span>{{ new Date() | moment('add', '6 days', 'calendar', null, { nextWeek: '[Happens in a week]' }) }}</span>
<!-- "Happens in a week" -->

For more information about moment#calendar, check out http://momentjs.com/docs/#/displaying/calendar-time/.

add

Mutates the original Moment by adding time.

<span>{{ someDate | moment("add", "7 days") }}</span>
<!-- or with multiple keys -->
<span>{{ someDate | moment("add", "1 year, 3 months, 30 weeks, 10 days") }}</span>

For more information about moment#add, check out http://momentjs.com/docs/#/manipulating/add/.

subtract

Works the same as add, but mutates the original moment by subtracting time.

<span>{{ someDate | moment("subtract", "3 hours") }}</span>

For more information about moment#subtract, check out http://momentjs.com/docs/#/manipulating/subtract/.

timezone

Convert the date to a certain timezone

<span>{{ date | moment('timezone', 'America/Los_Angeles', 'LLLL ss')}}</span>

To use this filter you will need to pass moment-timezone through to the plugin

// main.js
import Vue from 'vue'
import VueMoment from 'vue-moment'
import moment from 'moment-timezone'

Vue.use(VueMoment, {
    moment,
})

For more information about moment#timezone, check out https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/.

Chaining

There's some built-in (and not thoroughly tested) support for chaining, like so:

<span>{{ someDate | moment("add", "2 years, 8 days", "subtract", "3 hours", "ddd, hA") }}</span>

This would add 2 years and 8 months to the date, then subtract 3 hours, then format the resulting date.

Durations

vue-moment also provides a duration filter that leverages Moment's ability to parse, manipulate and display durations of time. Durations should be passed as either: a String of a valid ISO 8601 formatted duration, a Number of milliseconds, an Array containing a number and unit of measurement (for passing a number other than milliseconds), or an Object of values (for when multiple different units of measurement are needed).

<span>{{ 3600000 | duration('humanize') }}</span>
<!-- "an hour" -->
<span>{{ 'PT1800S' | duration('humanize') }}</span>
<!-- "30 minutes" -->
<span>{{ [35, 'days'] | duration('humanize', true) }}</span>
<!-- "in a month" -->

This filter is purely a pass-through proxy to moment.duration methods, so pretty much all the functions outlined in their docs are callable.

<span>{{ [-1, 'minutes'] | duration('humanize', true) }}</span>
<!-- "a minute ago" -->
<span>{{ { days: 10, months: 1 } | duration('asDays') }}</span>
<!-- "40" -->
<span>{{ 'P3D' | duration('as', 'hours') }}</span>
<!-- "72" -->

For manipulating a duration by either subtraction or addition, first use the relevant filter option, then chain your duration display filter.

<span>{{ [1, 'minutes'] | duration('subtract', 120000) | duration('humanize', true) }}</span>
<!-- "a minute ago" -->
<span>{{ [-10, 'minutes'] | duration('add', 'PT11M') | duration('humanize', true) }}</span>
<!-- "in a minute" -->
<span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span>
<!-- "3 years" -->

duration is for contextless lengths of time; for comparing 2 dates, use the diff method rather than hacking around with Moment durations. For more information about moment#duration, check out https://momentjs.com/docs/#/durations/.

Configuration

vue-moment should respect any global Moment customizations, including i18n locales. For more info, check out http://momentjs.com/docs/#/customization/.

You can also pass a custom Moment object through with the plugin options. This technique is especially useful for overcoming the browserify locale bug demonstrated in the docs http://momentjs.com/docs/#/use-it/browserify/

const moment = require('moment')
require('moment/locale/es')

Vue.use(require('vue-moment'), {
    moment
})

console.log(Vue.moment().locale()) //es

this.$moment

vue-moment attaches the momentjs instance to your Vue app as this.$moment.

This allows you to call the static methods momentjs provides.

If you're using i18n, it allows you to change the locale globally by calling this.$moment.locale(myNewLocale)

vue-moment's People

Contributors

andrew avatar brockpetrie avatar brockreece avatar dependabot[bot] avatar fercreek avatar hardlymirage avatar isidentical avatar joostdecock avatar mc100s avatar n3gotium avatar ramytamer avatar wilk avatar wlepinski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-moment's Issues

[BUG] Weekdays language set only on second render

this.$moment().format('MMM') and this.$moment().format('dddd') is showing the text in English during the first render.

During the second render, however, they appear in the locale language.

As a curiosity, when it's in English, the first letter is uppercase, while with the locale is lowercase.

I've tried moving the first render call from created() to mounted(), but it didn't work.

Any idea of what's going on?

template filter is not reactive

Hello

I display a date like so :

{{ realTime | moment }}

And update it every second like this :

        data() {
            return {
                realTime: this.$moment()
            };
        },

        created() {
            setInterval((() => { 
                    this.realTime.add(1, 'second')
                    console.log(this.realTime.format());
                }).bind(this), 
                1000);
        }

the console.logshows the updated value correctly, but the value displayed in the template remains the same...

Any idea ?

Thanks !

Duration feature

Is it possible to add Vue duration filter with expected output format?

Like in Moment
moment.duration(2, 'weeks');

Issue when i setup locale to de

I have the following setup to show date in german format:

const moment = require('moment');
require('moment/locale/de');

Vue.use(require('vue-moment'), {
    moment
});

and value of property is

plan.date = Wed, 25 Oct 2017 15:08:29 GMT (which is sent from backend)

When I do plan.date | moment('DD.MM.YYYY') I get the value as 25.01.2017.

How is this possible? Am I doing anything wrong?

Set vue-moment to default always to UTC time

I saw with the latest 4.0.0 release the addition of the utc function.

So I can now do:

{{ someDate | moment("utc", "YYYY-MM-DD HH:mm") }}

and it works fine.

But I cannot find a way to configure vue-moment to always use UTC.

Is this a limitation of moment or vue-moment or is it just me just not knowing how to default it like this?

Failed to resolve filter: moment

I'm including moment as follows

import * as moment from 'moment';
Vue.use(moment);

But I'm getting the following error. Do I need to pass the moment instance somewhere in my components? Thank you

moment from not working

I have a line like this:

<small class="text-muted">{{comment.created_at | moment from true}}</small>

While 'comment.created_at' is mysql datetime formatted date.
But i'm getting Uncaught TypeError: Cannot read property 'replace' of undefined.

Any idea why?

'moment calendar' is the same but 'moment "dddd, MMMM Do YYYY, h:mm:ss a"' is working good.

this.$moment().locale(lang) does not works

Hello, I want to change locale with a user click event on button.

I have the following

// main.js
import Vue from 'vue'
import VueMoment from 'vue-moment'
const moment = require('moment')
require('moment/locale/en-gb')
require('moment/locale/fr')
Vue.use(VueMoment, {
  moment
})

And then, using in component:

// app.vue
<script>
  methods: {
    setLanguage (lang) {
      console.log(lang)
      this.$moment().locale(lang)
      console.log(this.$moment().locale())
    }
  }
}
</script>

When I call the function from the button, I got the following

setLanguage('en')
en
fr
setLanguage('fr')
fr
fr

Is it possible to update the moment locale this way?

Warning on iso8601 string date

Hi,
I have a formated date on ISO8601 format: 2018-01-01T00:00:00+01:00
And have a warning on this string:

vue-moment.js:39 Could not build a valid moment object from input.

Have a solution ?

Allow numbers when specifying date format

I want to transform months from format M to MMMM.
The datatype is integer, which throws the error: Could not build a valid moment object from input.

Casting the integer to a string works but does not look really clean.

      {{ [ 2 + '', 'M' ] | moment('MMMM') }}  // displays "February" without an error
      {{ [ 2 , 'M' ] | moment('MMMM') }} // displays "[ 2 , 'M' ]" and logs error

I guess it is because the first value in an array is expected to be a string.
Could number work there as well?

https://github.com/brockpetrie/vue-moment/blob/master/vue-moment.js#L20
Something like this: if (Array.isArray(input) && ['string', 'number'].includes(typeof input[0]))

publish on npm?

Neat little collection of filters. You should publish them on npm for easy install ๐Ÿ‘

moment is not defined

I am getting the error above.

I have done the following

  1. npm install moment
  2. In the app.js file, I have tried both of the following:
import moment from vue-moment;
Vue.use(moment);
  1. npm run dev
  2. do a console.log(moment());
  3. got error: moment is not defined in the debug console

add LICENSE file

It would be great to have a LICENSE file in the project. This should be easy to do.

Duplicate moment instances when using moment.js in the project.

I have a project in which I use moment.js and vue-moment, I found out that vue-moment requires moment again in it's own package in node_modules. In that way we have a duplicate resources.

I understand that this is required in case one does not use moment.js in the first place. But in my case it's really important to me to reduce the build size.

Is there any way to make vue-moment use the same moment resource I use?

When I include vue-moment.min.js I get a error

Hi there,

I keep getting this error when I add vue-moment.min.js to the page:
Global Code โ€” vue-moment.min.js:1 ReferenceError: Can't find variable: require

moment.js and vue.js are loaded before. Any idea?

Thanks

npm install vue-moment remove other vue add-in

why npm install vue-moment it removes other add-in such as vue-datetime.
what I have done is

  1. npm install vue-datetime
  2. npm install vue-moment
  3. npm run dev --> prompt error vue-datetime not found, I check the directory is removed

UNIX Timestamp

I can't find a way to make it work with UNIX timestamps. Is it possible or did you cut off this feature?

Moment.js states you can do moment.unix(value).format("MM/DD/YYYY") but how can I do this with your filter?

Filter for Converting Between Timezones

PR #51 adds moment-timezone filters to vue-moment.

But I'm not sure how to convert from one timezone to another.

What I want to do is convert from UTC to America/Chicago like so:

moment.tz(date, 'UTC').clone().tz('America/Chicago');

I would imagine the API would be something like:

<span>{{ date | moment('timezone', 'UTC', 'clone', 'timezone', 'America/Chicago') }}</span>

Or the API could be smart and allow something like:

<span>{{ date | moment('timezone', 'UTC', 'America/Chicago') }}</span>

Maybe @BrockReece could answer the question of whether or not this is currently possible and provide a code snippet if it is?

Unmet peer dependency

npm install --save vue-moment fails, because UNMET PEER DEPENDENCY vue@^1.x.x even though I have "vue": "^1.0.21" installed. Could it be that npm has a problem parsing your required version string?

Deprecation warning: moment construction falls back to js Date

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to moment/moment#1407 for more info.
Arguments: [object Object]
Error
at Function.createFromInputFallback (http://localhost:8080/build/build.js:46871:106)
at configFromString (http://localhost:8080/build/build.js:47769:33)
at configFromInput (http://localhost:8080/build/build.js:48275:14)
at prepareConfig (http://localhost:8080/build/build.js:48258:14)
at createFromConfig (http://localhost:8080/build/build.js:48225:45)
at createLocalOrUTC (http://localhost:8080/build/build.js:48307:17)
at local__createLocal (http://localhost:8080/build/build.js:48311:17)
at utils_hooks__hooks (http://localhost:8080/build/build.js:46616:30)
at VueComponent. (http://localhost:8080/build/build.js:46493:13)
at VueComponent.Vue._applyFilters (http://localhost:8080/build/build.js:17001:19)

warn from moment.js.
vue-moment probably needs to change constructor for original moment.js objects

[feature request] Allow time comparison as conditional

<div v-if="moment().isBefore(otherTime)"></div><div v-else></div>

It would be awesome if we had something for this, except at the moment of inflection (when moment().isBefore(otherTime)'s status changes from true to false) Vue is able to detect it as a change and react accordingly.

Here is a similar discussion, but did not provide a clean API for accomplishing this. vuejs/Discussion#214

Unix timestamp in ms not working

After updating from 2.2.0 to the lastest version (3.1.0) it appears that the timestamp input must be provided in seconds, not milliseconds. Many timestamps are given in ms, including the JS Date object. I previously rolled back to 2.2.0 from a newer release because I thought it was a bug, but since it's still there I am wondering if the change was intentional.

Thanks for the help!

2 minutes ago

Is the human diff format possible using this plugin?
Thank you!

vue-moment + nuxt (webpack)

It looks like the most recent release of moment 2.19.0 has caused issues with vue-moment and webpack...

[web - 93095]: WARNING Compiled with 1 warnings4:56:47 PM
[web - 93095]: This relative module was not found:
[web - 93095]: * ./locale in ./node_modules/moment/src/lib/locale/locales.js

Does anyone have a workaround for this?

Support options on calendar

Hello,

The latest versions of moment support an options parameter when calling calendar, would be nice if vue-moment support it ๐Ÿ˜‰

Syntax example

<span>{{ new Date() | moment("calendar", null, { sameDay: '[Today]' }) }}</span>
<!-- e.g. "Today" -->

Conditional moment require still always results in included nested dependency

This may be a webpack or other issue, but thought its good to be aware of it.

I am using moment in other parts of my code so I have it imported via ES imports and so on, so I am passing it in manually like

import moment from 'moment';
Vue.use(require('vue-moment'), {moment: moment});

All is good, but when I use https://github.com/webpack-contrib/webpack-bundle-analyzer to check out what's actually outputted in my bundle, I see that the conditional require('moment') in this library is actually causing the code to be included in the bundle.
I can confirm that removing that 1 conditional line makes the nested moment not load anymore in the bundle.

Very confuzzled, any ideas?
Thanks!

Adopt code styling rules

@BrockReece I'm going to go through and clean up the code a bit. Any JS style guide you prefer? I'm partial to Airbnb, but willing to go with something different if you hate it.

Is it possible to use moment inside a method?

I didn't see in the documentation any explanation on how to use moment inside mounted/computed/methods... so I tried this:

 console.log(this.$moment(new Date()).add('7 days', 'dddd, MMMM Do YYYY'))

But it doesn't seem to work. ๐Ÿ˜ข (returning whole Moment object in the console)

Hope someone can help ๐Ÿ™‚

Thanks

Exclude locale files in build bundle.

When I I vue-cli and build a prod version, all locale files are build within bundle. It makes the bundle size is about 200k bigger than without them.

How can I exclude these files in build?

Feature request: when given empty string it should output an error message that is customizable.

Hi there, first thanks for this library it works like a charm !! I just love using it instead of directly hooking momentJS to the project. the only drawback I can see is that when given an empty string as the date to filter it outputs the date of today and there is no way to check on a data if it's empty or not before filtering it in vueJS.

So my proposition is adding a methods mixin so we can use the moment() as a function if filters are not the solution the situation.

And thanks for your time.

moment from, update automatic

Hi,

First of all, great package.

Is it possible to update all filters every minute. now the from now filter will stay on the time it's calculated. It would be great if those would update when a minute has passed. so a minute ago would turn into two minutes ago etc..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.