Git Product home page Git Product logo

ember-moment's Introduction

ember-moment

npm Version Build Status Ember Observer Score

moment.js template helpers for Ember.js

Compatibility

  • Ember.js v3.16 or above
  • Ember CLI v2.13 or above
  • Node.js v10 or above
  • ember-auto-import 2.0 or above

Using Moment.js in Ember Apps & Addons

This addon provides Ember-specific Helpers and a Service that make it convenient to use Moment.js in your templates. If you just want to call Moment.js directly from Javascript, you don't need this addon.

The recommended way to use Moment.js in an Ember app is:

  1. Add either moment or moment-timezone to your dependencies.
  2. Make sure you have ember-auto-import in your dependencies.
  3. Make sure you don't have ember-cli-moment-shim in your dependencies (it would add a redundant copy).
  4. Use imports in your Javascript like import moment from 'moment' or import moment from 'moment-timezone'.
  5. Optional but strongly recommended: Configure which locales and timezones will be included in your app by following the instructions below in "Controlling Locale and Timezone Data".

The recommended way to use Moment.js in an Ember addon is:

  1. Add either moment or moment-timezone to your peerDependencies. This ensures that your addon and the app must use the same copy.
  2. Also add it to your devDependencies so your own test suite satisfies the peerDep.
  3. Make sure you don't depend on ember-cli-moment-shim.
  4. Make sure you do depend on ember-auto-import.

Moment itself is no longer actively developed and new projects should not add it. You can look at alternative libraries like Luxon, or better yet keep an eye on Temporal which is likely to add moment-like capabilities directly to Javascript quite soon.

Controlling Locale and Timezone Data

Apps should configure their locale and timezone support (which can have a large impact on bundle size) by following Moment's documentation about Webpack:

and passing the resulting webpack configuration to either ember-auto-import or Embroider. For example:

const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MomentTimezoneDataPlugin = require('moment-timezone-data-webpack-plugin');

module.exports = function (defaults) {
  let app = new EmberApp(defaults, {
    autoImport: {
      webpack: {
        plugins: [
          new MomentLocalesPlugin({
            // 'en' is built into moment and cannot be removed. This strips the others.
            localesToKeep: [], 
          }),

          new MomentTimezoneDataPlugin({
            // Keep timezone data for the US, covering all possible years.
            matchCountries: 'US',
          }),
        ],
      },
    },
  });

Installing or Upgrading ember-moment

  1. First, install Moment.js using the instructions above.
  2. Then you can install ember-moment: ember install ember-moment

Compatibility:

  • Ember Octane+ : >= v9 // the default branch

  • Ember Classic : < v9 // the ember-classic branch.

    the ember-classic branch is in maintenance mode, and will only receive bugfixes

Usage

Helpers

moment

{{moment <date>}}
Parameters Values
<date> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)

Returns a Moment.

Example

{{moment '12-25-1995' 'MM-DD-YYYY'}} {{!-- Mon Dec 25 1995 00:00:00 GMT-0500 --}}

utc

{{utc <date>}}
{{utc}}
Parameters Values
<date> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)

Returns a Moment with utc mode set.

Example

{{utc '2001-10-31T08:24:56'}} {{!-- Wed Oct 31 2001 08:24:56 GMT+0000 --}}
{{utc}} {{!-- current time utc, like Mon Feb 12 2018 20:33:08 GMT+0000 --}}
{{utc (moment '2018-01-01T00:00:00+01:00' 'YYYY-MM-DD HH:mm:ssZ')}}  {{!-- Sun Dec 31 2017 23:00:00 GMT+0000 --}}

moment-format

{{moment-format <date> [outputFormat=moment.defaultFormat [<inputFormat>]]}}
Parameters Values
<date> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
outputFormat An optional date/time String output format, defaults to moment.defaultFormat which you must explicitly define
<inputFormat> An optional date/time String input format

Formats a <date> to an optional outputFormat from an optional inputFormat. If the inputFormat is not provided, the date String is parsed on a best effort basis. If the outputFormat is not given the global moment.defaultFormat is used. Typically, outputFormat and inputFormat are given. See momentjs#format.

NOTE: for all other helpers, the input format string is the second argument.

Example

{{moment-format '12-1995-25' 'MM/DD/YYYY' 'MM-YYYY-DD'}} {{!-- 12/25/1995 --}}

moment-from / moment-from-now

{{moment-from <dateA> [<dateB>] [hideAffix=false]}}
{{moment-from-now <dateA> [hideAffix=false]}}
Parameters Values
<dateA> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateB> An optional value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...), defaults to now
hideAffix An optional Boolean to hide the relative prefix/suffix or not.

Returns the time between <dateA> and <dateB> relative to <dateB>. See momentjs#from.

Note that moment-from-now is just a more verbose moment-from without dateB. You don't need to use it anymore.

Examples

{{!-- in January 2018 at time of writing --}}
{{moment-from '2995-12-25'}} {{!-- in 978 years --}}
{{moment-from-now '2995-12-25'}} {{!-- in 978 years --}}
{{moment-from '1995-12-25' '2995-12-25' hideAffix=true}} {{!-- 1000 years --}}

moment-to / moment-to-now

{{moment-to <dateA> [<dateB>] [hideAffix=false]}}
{{moment-to-now <dateA> [hideAffix=false]}}
Parameters Values
<dateA> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateB> An optional value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...), defaults to now
hideAffix An optional Boolean to hide the relative prefix/suffix or not.

Returns the time between <dateA> and <dateB> relative to <dateA>. See momentjs#to.

Note that moment-to-now is just a more verbose moment-to without dateB. You don't need to use it anymore.

Examples

{{!-- in January 2018 at time of writing --}}
{{moment-to '2995-12-25'}} {{!-- 978 years ago --}}
{{moment-to '1995-12-25' '2995-12-25'}} {{!-- in 1000 years --}}
{{moment-to-now '1995-12-25' hideAffix=true}} {{!-- 22 years --}}

moment-duration

{{moment-duration <number> [<units>]}}
Parameters Values
<number> Any value(s) interpretable as a duration by moment (typically a Number in milliseconds)
<units> An optional String to specify the units of <number> (typically 'seconds', 'minutes', 'hours'...)

Returns a Duration automatically humanized. See momentjs#duration.

Examples

{{moment-duration 100}} {{!-- a few seconds --}}
{{moment-duration 24 'hours'}} {{!-- a day --}}

moment-calendar

{{moment-calendar <dateA> [<dateB> [<formatHash>]]}}
Parameters Values
<dateA> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateB> An optional value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...) used as a reference, defaults to now
<formatHash> An optional output format hash, defaults to {}

Returns the time between <dateA> and <dateB> relative to <dateB> in a way that is different from moment-from and customizable via <formatHash>. See momentjs#calendar.

Examples

{{!-- in January 2018 at time of writing --}}
{{moment-from-now '2018-01-25'}} {{!-- 2 days ago --}}
{{moment-calendar '2018-01-25'}} {{!-- Yesterday at 12:00 AM --}}

moment-diff

{{moment-diff <dateA> <dateB> [precision='milliseconds' [float=false]]}}
Parameters Values
<dateA> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateB> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
precision An optional unit of measurement, defaults to 'milliseconds'
float An optional Boolean to get the floating point result, rather than the integer value

Returns the difference in precision units between <dateA> and <dateB> with floating point accuracy if float is true. See momentjs#diff.

Examples

{{moment-diff '2018-01-25' '2018-01-26'}} {{!-- 86400000 --}}
{{moment-diff '2018-01-25' '2018-01-26' precision='years' float=true}} {{!-- 0.0026881720430107525 --}}

moment-add

{{moment-add <date> <number> [precision='milliseconds']}}
Parameters Values
<date> An optional value interpretable as a date/time by moment (a date String or a Moment or a Date...). Defaults to value of moment()
<number> Any value(s) interpretable as a duration by moment that is the amount of the precision you want to add to the date provided
precision An optional unit of measurement, defaults to 'milliseconds'

Mutates the original moment by adding time. See momentjs#add.

Examples

{{!-- Add 6 days to a date --}}
{{moment-add '10-19-2019' 6 precision='days'}}

{{!-- Add 6 days to a date --}}
const duration = { days: 6 }
{{moment-add '10-19-2019' duration}}

{{!-- Print a date 6 days from now --}}
{{moment-add 6 precision='days'}}

moment-subtract

{{moment-subtract <date> <number> [precision='milliseconds']}}
Parameters Values
<date> An optional value interpretable as a date/time by moment (a date String or a Moment or a Date...). Defaults to value of moment()
<number> Any value(s) interpretable as a duration by moment that is the amount of the precision you want to subtract from the date provided
precision An optional unit of measurement, defaults to 'milliseconds'

Mutates the original moment by removing time. See momentjs#subtract.

Examples

{{!-- Remove 6 days from a date --}}
{{moment-subtract '10-19-2019' 6 precision='days'}}

{{!-- Remove 6 days from a date --}}
const duration = { days: 6 }
{{moment-subtract '10-19-2019' duration}}

{{!-- Print a date 6 days earlier --}}
{{moment-subtract 6 precision='days'}}

is-before / is-after / is-same / is-same-or-before / is-same-or-after

{{is-before <dateA> [<dateB>] [precision='milliseconds']}}
{{is-after <dateA> [<dateB>] [precision='milliseconds']}}
{{is-same <dateA> [<dateB>] [precision='milliseconds']}}
{{is-same-or-before <dateA> [<dateB>] [precision='milliseconds']}}
{{is-same-or-after <dateA> [<dateB>] [precision='milliseconds']}}
Parameters Values
<dateA> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateB> An optional value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...). If not given, <dateA> becomes now and <dateB> becomes <dateA>
precision An optional String unit of comparison precision, defaults to 'milliseconds'

Returns a Boolean that indicates if <dateA> is respectively before/after/the same/same or before/ same or after <dateB> to the precision level. See momentjs#queries.

Examples

{{is-before '2995-12-25'}} {{!-- false --}}
{{is-before '2018-01-25' '2018-01-26' precision='years'}} {{!-- false --}}
{{is-same-or-after '2018-01-25' '2018-01-26' precision='years'}} {{!-- true --}}

is-between

{{is-between <date> <dateA> [<dateB>] [precision='year' inclusivity='[)']}}
Parameters Values
<date> Any value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateA> A boundary value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...)
<dateB> An optional boundary value(s) interpretable as a date/time by moment (a date String or a Moment or a Date...). If not given <date> is assigned now, <dateA> is assigned <date> and <dateB> is assigned <dateA>.
precision An optional String unit of comparison precision, defaults to 'milliseconds'
inclusivity An optional String indicating inclusivity of the boundaries, defaults to ()

Returns a Boolean that indicates if <date> is between <dateA> and <dateB> to the precision level and with boundary inclusions specified by inclusivity. See momentjs#is-between.

Examples

{{is-between '1995-12-25' '2995-12-25'}} {{!-- true --}}
{{is-between '1995-12-25' '1995-12-25' '2995-12-25' precision='years' inclusivity='()'}} {{!-- true --}}

now

{{now}}
{{moment-format (now) 'MM-DD-YYYY'}}

Returns the present Moment.

Examples

{{!-- date at time of writing }}
{{now}} {{!-- Sat Jan 27 2018 11:59:31 GMT-0500 --}}
{{!-- interval is a common named parameter (see the corresponding section) }}
{{now interval=1000}} {{!-- <current date and updating every 1-second (1000 milliseconds).> --}}

unix

{{unix <timestamp>}}
Parameters Values
<timestamp> An integer Number or String value representing the number of seconds since the Unix Epoch (January 1 1970 12AM UTC)

Returns a Moment corresponding to the <timestamp>.

Examples

{{unix '1516586508'}} {{!-- Sun Jan 21 2018 21:01:48 GMT-0500 --}}
{{!-- Warning: Passing a literal integer value does not work --}}
{{unix 1516586508}} {{!-- Invalid date --}}

Common optional named arguments

All helpers accept the following optional named arguments (even though they are not always applicable):

Parameters Values
locale An optional String locale, to override the default global moment.locale
timeZone An optional String time zone, defaults to moment.timeZone (the default time zone)
interval An optional interval Number of milliseconds when the helper should be recomputed
allow-empty An optional Boolean to ignore the Invalid date output when knowingly passing null, undefined, or '', defaults to false

Note that interval does not recompute the value of the helper parameters, unless it is part of a helper that is a value in which case it is useful for "live" updating as time elapses.

Warning: allow-empty is currently inconsistent and should not always be trusted.

Examples

{{now interval=1000}} {{!-- <current date and updating every 1-second (1000 milliseconds)> --}}
{{is-before (now) '2018-01-26' interval=60000}} {{!-- if this was true initially, it will always be true despite interval --}}
{{moment-format '' allow-empty=true}}  {{!-- <nothing> --}}

Configuration Options

Global Default Output Format

Your application may require a default format other than the default, ISO 8601. For example, you may want dates to fallback on the localized shorthand format L by default.

// config/environment.js
module.exports = function() {
  return {
    moment: {
      outputFormat: 'L'
    }
  }
};

If you need to change the default format during runtime, use the service API. Doing so will cause the moment-format helper instances to re-render with the new default format.

// app/controller/index.js
export default Ember.Controller.extend({
  moment: Ember.inject.service(),
  actions: {
    changeDefaultFormat() {
      this.set('moment.defaultFormat', 'MM.DD.YYYY');
    }
  }
})

Global Allow Empty Dates

If null, undefined, or an empty string are passed as a date to any of the moment helpers then you will get Invalid Date in the output. To avoid this issue globally, you can set the option allowEmpty which all of the helpers respect and will result in nothing being rendered instead of Invalid Date.

// config/environment.js
module.exports = function() {
  return {
    moment: {
      allowEmpty: true // default: false
    }
  }
};

Configure default runtime locale/timeZone

Globally set locale

// app/routes/applicaton.js
export default Ember.Route.extend({
  moment: Ember.inject.service(),
  beforeModel() {
    this.get('moment').setLocale('es');
  }
});

Globally set time zone

// app/routes/applicaton.js
export default Ember.Route.extend({
  moment: Ember.inject.service(),
  beforeModel() {
    this.get('moment').setTimeZone('America/Los_Angeles');
  }
});

Frequently Asked Questions

Invalid Date is being rendered into the DOM, how do I avoid this?

An invalid date string is being passed into momentjs and/or the input string format was omitted.

If you are knowingly passing null, undefined, or an empty string and want to ignore the output of Invalid Date then pass the option allow-empty=true to the helper (all helpers accept this property)

{{moment-format ''}}  {{!-- Invalid date --}}
{{moment-format '' allow-empty=true}}  {{!-- <nothing> --}}

Contributing

See the Contributing guide for details.

Docs to add

ember-moment's People

Contributors

akatov avatar alexlafroscia avatar aureliosaraiva avatar btecu avatar chancancode avatar cibernox avatar clov3r avatar crotwell avatar ctjhoa avatar dependabot[bot] avatar ef4 avatar elidupuis avatar fenekku avatar greatwizard avatar jasonmit avatar jcope2013 avatar jmurphyau avatar locks avatar lukemelia avatar mbinet avatar nullvoxpopuli avatar patsy-issa avatar pavolatzonky avatar raycohen avatar rounders avatar seanpdoyle avatar sly7-7 avatar stefanpenner avatar thomasdashney avatar yads 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

ember-moment's Issues

i18n - Locales not loaded?

Hi.

I am using ember-cli 1.13.8 and the latest release of ember-moment.

I need to handle French (fr-ca) and English (en-ca) locales so I did this in config/environment.js where the ENV object is populated with all the key/values:

// config/environment.js
ENV[ 'moment' ] = {
        includeLocales: [ 'en-ca', 'fr-ca']
    };

But English is the only locale available. I have tried several different ways to force the locale to switch to fr-ca and nothing happens.
It looks that the locales are not loaded so the default one (en) is picked up.

Could you please tell me what I am missing here?

Update:
The locales (en-ca, fr-ca) are correctly added to vendor.js so I have checked moment-format.js that I used to test my locales and it looks that the locale is just ignored.
In my template I have:
{{moment-format challenge.start_date 'DD MMMM YYYY' locale='fr-ca'}}

I have added some logging to moment-format.js:
image

Should I not see _abbr: 'fr-ca' ?

Languages

Is there an easy way to change the language?

Getting errors when trying to use the computed properties

Uncaught TypeError: Cannot read property 'indexOf' of undefined

ember.debug.js:12495 which is:

    @method
    @private
    @param {String} pattern The property pattern to expand.
    @param {Function} callback The callback to invoke.  It is invoked once per
    expansion, and is passed the expansion.
    */
  function expandProperties(pattern, callback) {
    if (pattern.indexOf(' ') > -1) {  // <<<<------ FAILING HERE
      throw new EmberError['default']('Brace expanded properties cannot contain spaces, ' +
        'e.g. `user.{firstName, lastName}` should be `user.{firstName,lastName}`');
    }

  // ..........
DEBUG: -------------------------------
ember.debug.js:5197DEBUG: Ember             : 1.11.1
ember.debug.js:5197DEBUG: Ember Data        : 1.0.0-beta.16.1
ember.debug.js:5197DEBUG: jQuery            : 2.1.3
ember.debug.js:5197DEBUG: Ember Simple Auth : 0.7.3
ember.debug.js:5197DEBUG: -------------------------------

Set allow-empty globally

It would be nice if I could set allow-empty globally.
In my application most of the dates are not well defined so i have to add to every {{moment-format}} the allow-empty=true parameter.

Since its possible to define the ouput format globally I think it should be possible to define allow-empty globally too.

What is 'config.environment.js'?

When I use ember-cli, placing moment parameters into config/environment.js ENV-variable provide no effect. Where moment-parameters should be?

This config won't work:

/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'client',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },
    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
      SERVER: 'http://10.10.39.12:10000/v0.3'
    },
    moment: {
      allowEmpty: true // default: false
    }
  };
...

Invalid date

Can we have a setting to handle 'null' dates silently?

Configurable default moment format

Right now moment format is hard coded to: LLLL. I've love the ability to globally set the default format to something else besides having to pass it into every moment function.

If at all possible it would be great to tie it to the locale enhancement so formats could changed based on language selected. (issue #14)

Can't install addon. Error: Cannot read property 'reduce' of undefined?

Hi,

After I upgraded to ember-cli 1.13.5 I cannot get ember-moment to install. I've used ember-moment before with previous projects and I assume this addon still works for other people so it must be an environmental thing, but I want to ask if there is a known work around for this type of issue?

I'm running on windows if that makes a difference.

ember install ember-moment
version: 1.13.5
Installed packages for tooling via npm.
installing ember-moment
  install addon ember-cli-moment-shim
Installed packages for tooling via npm.
Cannot read property 'reduce' of undefined
TypeError: Cannot read property 'reduce' of undefined
    at Class.module.exports.Task.extend.installBlueprint (C:\embercli\studentdashboard\client\node_modules\ember-cli\lib\tasks\addon-install.js:54:24)
    at Class.<anonymous> (C:\embercli\studentdashboard\client\node_modules\ember-cli\lib\tasks\addon-install.js:43:19)
    at lib$rsvp$$internal$$tryCatch (C:\embercli\studentdashboard\client\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:493:16)
    at lib$rsvp$$internal$$invokeCallback (C:\embercli\studentdashboard\client\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:505:17)
    at lib$rsvp$$internal$$publish (C:\embercli\studentdashboard\client\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:476:11)
    at lib$rsvp$asap$$flush (C:\embercli\studentdashboard\client\node_modules\ember-cli\node_modules\rsvp\dist\rsvp.js:1198:9)
    at process._tickCallback (node.js:340:13)

Ago Component Input Date for 2015-02-04T03:19:51.000Z

So, I've been using this for awhile on selby.io/blog and it's been bugging me.

I've been passing in sqlite's date format, which is like 2015-02-04T03:19:51.000Z:

{{ago post.created_at}}

And it gives a pseudo-random number of hours ago: 17 hours ago. Today I attempted to pass in an input format:

{{ago post.created_at "YYYY-MM-DDTHH:mm:ss.000Z"}}

But now it's giving me years. 2012 years ago

Any ideas? Thanks for any help you can give.

Great component, btw.

Add additional date format helpers from ember-cli-dates?

Hello,

I'm the maintainer of ember-cli-dates. There's definitely a lot of overlap between these two projects as pointed out in johno/ember-cli-dates/issues/19, so I was hoping to combine efforts and collaborate on a single, cohesive project. This project has significantly more functionality, but is missing some of the date helpers that ember-cli-dates currently provides.

So, I'm wondering if you all have any interest in adding some of the helpers like day-of-the-week, month-and-day, and month-and-year, etc.? I'd be happy to open up a PR if this is something that this project would be interesting in incorporating. Or, perhaps the helpers could be broken off into an ember-moment-helpers addon, which end users can optionally install in order to incorporate a collection of helpers regarding dates and times?

Any thoughts or insight would be greatly appreciated, I'd love to collaborate and combine efforts.

Best,

John Otander

error when installing addon

Hi, I've used this addon in the past with no problem, but today I've tried to install it on a project and it threw an error, now I've created a new ember cli project and installed the addon, this is the output:

➜  testApp git:(master) ✗ ember install ember-moment
version: 1.13.5
Installed packages for tooling via npm.
installing ember-moment
  install addon ember-cli-moment-shim
Installed packages for tooling via npm.
Cannot read property 'reduce' of undefined
TypeError: Cannot read property 'reduce' of undefined
    at Class.module.exports.Task.extend.installBlueprint (/Users/sebastianb/Projects/testApp/node_modules/ember-cli/lib/tasks/addon-install.js:54:24)
    at Class.<anonymous> (/Users/sebastianb/Projects/testApp/node_modules/ember-cli/lib/tasks/addon-install.js:43:19)
    at lib$rsvp$$internal$$tryCatch (/Users/sebastianb/Projects/testApp/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:493:16)
    at lib$rsvp$$internal$$invokeCallback (/Users/sebastianb/Projects/testApp/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:505:17)
    at lib$rsvp$$internal$$publish (/Users/sebastianb/Projects/testApp/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:476:11)
    at lib$rsvp$asap$$flush (/Users/sebastianb/Projects/testApp/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1198:9)
    at process._tickCallback (node.js:355:11)
➜  testApp git:(master) ✗

do you have any idea about what the error could be?

Add computedMoment

function computedMoment(date, format) {
  return Ember.computed(date, format, function() {
    return moment(this.get(date)).format(this.get(format));
  }).readOnly();
}

Usage:

dateShortFormat: `MM/DD`,
myShortDate: computedMoment('myDate, dateShortFormat')

Update as time passes?

This is to get thoughts on having the {{ago}} helper update as time passes..

I've been playing around with it but haven't got it quite there yet.. I've been doing it in HTMLBars only though - returning a stream that gets notified at the point in time that the string is expected to have changed.

Should the computed property and the helper update as time passes? For ago, I'm not really clear on the use cases for the computed property, if not to display in a template (which the helper covers).

  • 0 to 45 seconds = 'a few seconds ago'
  • 45 to 90 seconds = 'a minute ago'
  • 90 seconds to 45 minutes = '2 minutes ago ... 45 minutes ago'
  • 45 to 90 minutes = 'an hour ago'
  • 90 minutes to 22 hours = '2 hours ago ... 22 hours ago'
  • 22 to 36 hours = 'a day ago'
  • 36 hours to 25 days = '2 days ago ... 25 days ago'
  • 25 to 45 days = 'a month ago
  • 45 to 345 days = '2 months ago ... 11 months ago'
  • 345 to 547 days (1.5 years) = 'a year ago'
  • 548 days+ = '2 years ago ... 20 years ago'

Error: Assertion Failed: A helper named 'moment' could not be found

When I try to use

{{moment date}}

in a hbs file, i get the console error

Error: Assertion Failed: A helper named 'moment' could not be found

I've installed ember-moment successfully, ie,

$ ember install ember-moment
version: 0.2.7
Installed packages for tooling via npm.
installing
Installing browser packages via Bower...
  cached git://github.com/jasonmit/ember-cli-moment-shim.git#0.0.3
  new version for git://github.com/jasonmit/ember-cli-moment-shim.git#*
  resolved git://github.com/jasonmit/ember-cli-moment-shim.git#0.1.0
  cached git://github.com/moment/moment.git#2.10.3
Installed browser packages via Bower.
Installed addon package.

Please help

Path or pattern "vendor/moment/locales/en.js" did not match any files

I have a very strange problem. When using

 moment: {
    includeLocales: ["en"]
}

I get the error Path or pattern "vendor/moment/locales/en.js" did not match any files

It works when I change it to true instead. However, somehow after repeatedly clearing tmp, bower_components, node_modules, at some point it suddenly started working again, altough I haven't really changed anything. The problem also occured on a fresh install.

duration helpers?

I would love to see some duration helpers (assumes myDuration: 45):

{{duration myDuration "minutes"}}   // "an hour"
{{duration myDuration "minutes" "ago"}}  // "an hour ago"
{{duration myDuration "minutes" "in"}} // "in an hour"

There's probably a more elegant api surface but caffeine is in short supply at the moment.

style support?

I was thinking it might be quite helpful to have results from the helpers distinguish between the numeric component of the return versus the contextual text. For instance, if the result was "3 days" this might be better represented as:

<span class="numeric">3</span><span class="descriptive"> days</span>

I often find that making the descriptive text a slightly lighter colour helps the user understand the information more quickly. Admittedly I'm sure there would be some use cases where this would be disruptive but I'd guess it would be helpful or have no impact in a majority of cases.

Maybe added as a parameter:

{{ago myTime stylize:true}}

Thoughts?

Addon Woes with ember-cli 0.2.0 and ember 1.10.0

Hey Stefan, thanks for this!

I do note that in my current build (node 0.12.0, Vanilla ember-cli 0.2.0, ember 1.10.0) I get the following error, using moment in a transformer:

Error: Could not find module `ember-moment/helpers/moment` imported from `ember-app/initializers/ember-moment`. 

I really have nothing else going on, so not sure what's up, but it was working with a GLOBAL and Brocfile.js import on 0.15.0 and 1.9.0, so maybe something with the loader?

import DS from "ember-data";
import moment from 'ember-moment';

var IsodateTransform = DS.Transform.extend({  
  deserialize: function (serialized) {
    if (serialized) {
      return moment(serialized).toDate();
    }
    return serialized;
  },

  serialize: function (deserialized) {
    if (deserialized) {
      return moment(deserialized).format();
    }
    return deserialized;
  }
});

export default IsodateTransform;

Update version

Can we get a new release that includes duration helper?
It would be nice if it could be released on npm too...

0.2.3 installation issue

I am getting the following message at the end. That said, my app still works 💃

# ember install ember-moment
version: 0.2.3
Installed packages for tooling via npm.
installing
Installing browser packages via Bower.
Installing browser packages via Bower...
  cached git://github.com/jasonmit/ember-cli-moment-shim.git#0.0.3
  cached git://github.com/moment/moment.git#2.8.4
  new version for git://github.com/moment/moment.git#>=2.7.0
  resolved git://github.com/moment/moment.git#2.10.2
Installed browser packages via Bower.
installing
The `ember generate` command requires an entity name to be specified. For more details, use `ember help`.

Also, since ember install:addon is not valid on 0.2.3, please consider adding a note on the readme.txt file.

Cannot find module './key-for-file'

I'm getting this error after install.
I have installed ember cli 1.13.1, and ember 1.12.1
Help 😖

ember s
Cannot find module './key-for-file'
Error: Cannot find module './key-for-file'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/home/julian/Developer/work/freelancing/cvc-portal-livelo-ui/node_modules/ember-moment/node_modules/broccoli-stew/node_modules/cauliflower-filter/filter.js:14:18)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)

Can't load Timezones

Hi,

I'm attempting to load a list of zone names using moment.tz.names() and keep receiving an undefined error when calling the aforementioned method. Using devtools, it appears moment is defined, but tz is not. I've added the following to my environment.js file:

moment: {
    includeTimezone: 'all'
}

I'm calling moment.tz.names() through a service:

import Ember from 'ember';
import moment from 'moment';

export default Ember.Service.extend({
  us: Ember.computed(() => {
    return moment.tz.names();
  })
});

I'm using [email protected] and [email protected] with [email protected].

Thanks for the help!
James

allowEmpty destroys format?!

Now that allowEmpty can be set in global config it wont accept the global config for date format.

// environment.js 
moment: {
  outputFormat: 'DD.MM.YYYY',
  allowEmpty: true
},
// template.hbs
{{moment-format model.someDate}}

This will result in Friday, August 14, 2015 12:00 AM
It should print 14.08.2015.

I worked before the update, except from the allowEmpty which is working now :p

Can anybody confirm this? Am I missing something?

Ember-CLI test

I have a component that uses ago in its template. No problem compiling the template in development, but how do you include it in the test? I've tried various ways with no success.

<Ember._HandlebarsBoundView:ember300> Handlebars error: Could not find property 'ago' on object <(subclass of Ember.Component):ember298>.

issue testing page with moment-from-now

My acceptance tests stopped working in pages where I added the moment-from-now with an interval.

The tests start with visit to a url, followed by andThen containing the asserts.
Unfortunately the tests fail with a timeout and the andThen isn't called.

I'm guessing the problem is the endless Ember.runLater that the testing framework waiting for all the jobs queue to empty before activating the next andThen.

Without passing an interval to the moment-from-now the tests work as expected.

This issue isn't specific to ember-moment. It was reported to Ember since 2013 and still is open - see emberjs/ember.js#3008
@teddyzeenny provided a workaround in that thread, ie. instead of runLater use:
setTimeout(function() { Em.run(function() { //.. code here } });

moment.locale() does not work

Hi,

i tried using

// app/routes/applicaton.js
import moment from 'moment';

export default Ember.Route.extend({
  beforeModel() {
    // sets the application locale to Dutch
    moment.locale('nl');
  }
});

But it doesn't set the language at all, it still stays at 'en'. Anything else i need to configure first to make this work?
(im on the latest version)

Cannot read property 'name' of undefined

when ember install ember-moment I get:

version: 0.2.5
Installed packages for tooling via npm.
Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined
    at /Users/johndoe/frontend/node_modules/ember-cli/lib/models/project.js:475:53
    at baseFindIndex (/Users/johndoe/frontend/node_modules/ember-cli/node_modules/lodash/internal/baseFindIndex.js:16:9)
    at /Users/johndoe/frontend/node_modules/ember-cli/node_modules/lodash/internal/createFind.js:18:19
    at Project.findAddonByName (/Users/johndoe/frontend/node_modules/ember-cli/lib/models/project.js:474:20)
    at Class.module.exports.Task.extend.findDefaultBlueprintName (/Users/johndoe/frontend/node_modules/ember-cli/lib/tasks/addon-install.js:63:30)
    at Class.module.exports.Task.extend.installBlueprint (/Users/johndoe/frontend/node_modules/ember-cli/lib/tasks/addon-install.js:52:30)
    at Class.<anonymous> (/Users/johndoe/frontend/node_modules/ember-cli/lib/tasks/addon-install.js:42:19)
    at lib$rsvp$$internal$$tryCatch (/Users/johndoe/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:489:16)
    at lib$rsvp$$internal$$invokeCallback (/Users/johndoe/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:501:17)
    at lib$rsvp$$internal$$publish (/Users/johndoe/frontend/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:472:11)

and ember -v gives me:

version: 0.2.5
node: 0.12.2
npm: 2.10.0

Name helpers more inline with moment

It would be good to have ember-moment helpers follow Moment.js naming.
For instance, we have a helper called ago for relative time. It should probably be called fromNow or relative since it also works for future dates:

{{ago pastDate}} // 3 years ago
{{ago futureDate}} // in 2 weeks

moment helper is very generic named and maybe it would be better named format.
duration is named properly, since it's named exactly like that in Moment.js.

I realize those names are too generic, so maybe it would be better to prefix them, like moment-format, moment-duration ...

moment is not defined

I just upgraded from Ember CLI 0.2.7 to 1.13.1 and updated the ember-moment (npm: 2.0.0) and ember-cli-moment-shim (bower: 0.3.1) to the latest. I have install moment on the bower side at version 2.10.3.

Should be the latest and greatest for all but when I start serving the application the application compiles/transpiles I immediately get a:

Uncaught ReferenceError: moment is not defined

The stack trace is:

(anonymous function)    @   index.js:5
mod.state   @   loader.js:141
tryFinally  @   loader.js:21
requireModule   @   loader.js:139
requireFrom @   loader.js:112
reify   @   loader.js:97
mod.state   @   loader.js:140
tryFinally  @   loader.js:21
requireModule   @   loader.js:139
requireFrom @   loader.js:112
reify   @   loader.js:97
mod.state   @   loader.js:140
tryFinally  @   loader.js:21
requireModule   @   loader.js:139
requireFrom @   loader.js:112
reify   @   loader.js:97
mod.state   @   loader.js:140
tryFinally  @   loader.js:21
requireModule   @   loader.js:139
(anonymous function)    @   ember-load-initializers.js:24
default @   ember-load-initializers.js:21
(anonymous function)    @   app.js:15
mod.state   @   loader.js:141
tryFinally  @   loader.js:21
requireModule   @   loader.js:139
(anonymous function)    @   app-boot.js:25

Am I doing anything obviously wrong?

Setting locales from config file

Hi,

I've been trying to configure the locale for this addon but nothing happens when I change the environmnet.js or even when I manually set the local on a helper instance. So I wonder if the documentation refers to some config file other than the default in CLI, as it points to config.environment.js

Thanks,
Jorge L

Failed to install in a new ember app

Hi, I'm having the next problem.
Executing 'ember init' and immediately after 'ember install ember-moment' gives

version: 1.13.5
Could not find watchman, falling back to NodeWatcher for file system events.
Visit http://www.ember-cli.com/user-guide/#watchman for more info.
Installed packages for tooling via npm.
installing ember-moment
  install addon ember-cli-moment-shim
Installed packages for tooling via npm.
Cannot read property 'reduce' of undefined
TypeError: Cannot read property 'reduce' of undefined
    at Class.module.exports.Task.extend.installBlueprint (/home/neto/Development/new/node_modules/ember-cli/lib/tasks/addon-install.js:54:24)
    at Class.<anonymous> (/home/neto/Development/new/node_modules/ember-cli/lib/tasks/addon-install.js:43:19)
    at lib$rsvp$$internal$$tryCatch (/home/neto/Development/new/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:493:16)
    at lib$rsvp$$internal$$invokeCallback (/home/neto/Development/new/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:505:17)
    at lib$rsvp$$internal$$publish (/home/neto/Development/new/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:476:11)
    at lib$rsvp$asap$$flush (/home/neto/Development/new/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1198:9)
    at process._tickCallback (node.js:355:11)

I'm using using ember-cli 1.13.5

legacy-register initializer is incorrectly added to Ember 2.0.1 addon

I'm trying to use ember-moment as dependency of the ember-cp-validations addon. For some reason, the legacy-register initializer is getting included in the built application, even though the app is using Ember 2.0.1. I've created an extremely minimal ember addon where you can see the error in action—it's basically just an empty ember addon plus ember-moment. To see the problem, do this:

git clone https://github.com/indirect/ember-moment-initializer-demo
cd ember-moment-initializer-demo
bower install
npm install
ember serve

Then open http://localhost:4200 in your browser, and check the console to see the initializer throwing an exception by trying to use an API that has been removed in Ember 2.

I spent a bunch of time trying to debug this, and as far as I can tell, the ember-moment index.js file is correctly able to tell that the app is using Ember 2, and the treeForApp does not actually include the initializer. In spite of that, however, the tree for the final dummy application for this addon does somehow include it. My extremely hacky solution to this problem was to add this to my ember-cli-build.js:

  app.appAndDependencies = function() {
    var tree = EmberApp.prototype.appAndDependencies.apply(this, arguments);
    return stew.rm(tree, 'broken-moment-demo/initializers/legacy-register.js');
  };

Any help figuring out how this initializer is ending up in the build tree, and how to stop that from happening, would be great. :)

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.