Coder Social home page Coder Social logo

react-moment's Introduction

react-moment

React component for the moment date library.

Build Status Coverage Status NPM Downloads MIT License

Installing

Node 8 or greater is required. Use npm to install react-moment along with its peer dependency, moment.

npm install --save moment react-moment

Timezone Support

The moment-timezone package is required to use the timezone related functions.

npm install --save moment-timezone

Then import the package into your project.

import React from 'react';
import Moment from 'react-moment';
import 'moment-timezone';

export default class App extends React.Component {
    ...
}

Quick Start

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment>{dateToFormat}</Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>

The above example could also be written this way if you prefer to pass the date using an attribute rather than as a child to <Moment>.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment date={dateToFormat} />
        );
    }
}

The date value may be a string, object, array, or Date instance.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = new Date('1976-04-19T12:59-0500');
            <Moment date={dateToFormat} />
        );
    }
}

Props

The component supports the following props. See the Moment docs for more information.

Interval

interval={number}

By default the time updates every 60 seconds (60000 milliseconds). Use the interval prop to change or disable updating.

Updates the time every 30 seconds (30000 milliseconds).

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment interval={30000}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Disables updating.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment interval={0}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Formatting

format={string}

Formats the date according to the given format string. See the Moment docs on formatting for more information.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment format="YYYY/MM/DD">
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time>1976/04/19</time>

For Duration and DurationFromNow formatting, the formatting is done using a separate library. See the Moment-Duration-Format docs on formatting for more information.

import React  from 'react';
import Moment from 'react-moment';
import moment from 'moment';

export default class MyComponent extends React.Component {
    const start = moment().add(-4, 'm');
    render() {
        return (
        <Moment date={start} format="hh:mm:ss" durationFromNow />
        );
    }
}

Outputs:

<time>00:04:00</time>

Trim

trim={string|bool}

When formatting duration time, the largest-magnitude tokens are automatically trimmed when they have no value. See the Moment-Duration-Format docs on trim for more information.

import React  from 'react';
import Moment from 'react-moment';
import moment from 'moment';

export default class MyComponent extends React.Component {
    const start = moment().add(-4, 'm');
    render() {
        return (
        <Moment date={start} format="hh:mm:ss" trim durationFromNow />
        );
    }
}

Outputs:

<time>04:00</time>

Parsing Dates

parse={string}

Moment can parse most standard date formats. Use the parse attribute to tell moment how to parse the given date when non-standard. See the Moment docs on parsing for more information.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment parse="YYYY-MM-DD HH:mm">
                1976-04-19 12:59
            </Moment>
        );
    }
}

Add and Subtract

add={object}

subtract={object}

Used to add and subtract periods of time from the given date, with the time periods expressed as object literals. See the Moment docs on add and subtract for more information.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        const date = new Date();

        return (
            <div>
                <Moment add={{ hours: 12 }}>{date}</Moment>
                <Moment add={{ days: 1, hours: 12 }}>{date}</Moment>
                <Moment subtract={{ hours: 12 }}>{date}</Moment>
                <Moment subtract={{ days: 1, hours: 12 }}>{date}</Moment>
            </div>
        );
    }
}

From Now

fromNow={bool}

Sometimes called timeago or relative time, displays the date as the time from now, e.g. "5 minutes ago".

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment fromNow>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>40 years ago</time>

Including ago with fromNow will omit the suffix from the relative time.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment fromNow ago>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>40 years</time>

From Now During

fromNowDuring={number}

Setting fromNowDuring will display the relative time as with fromNow but just during its value in milliseconds, after that format will be used instead.

From

from={string}

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment from="2015-04-19">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>39 years</time>

To Now

toNow={bool}

Similar to fromNow, but gives the opposite interval.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment toNow>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>40 years ago</time>

To

to={string}

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment to="2015-04-19">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>39 years</time>

Filter

filter={function}

A function which modifies/transforms the date value prior to rendering.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        const toUpperCaseFilter = (d) => {
            return d.toUpperCase();
        };

        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment filter={toUpperCaseFilter}>{dateToFormat}</Moment>
        );
    }
}

Outputs:

<time>MON APR 19 1976 12:59:00 GMT-0500</time>

With Title

withTitle={bool}

Adds a title attribute to the element with the complete date.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment format="D MMM YYYY" withTitle>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time title="1976-04-19T12:59-0500">19 Apr 1976</time>

Title Format

titleFormat={string}

How the title date is formatted when using the withTitle attribute.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment titleFormat="D MMM YYYY" withTitle>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time title="19 Apr 1976">1976-04-19T12:59-0500</time>

Difference

diff={string}

decimal={bool}

unit={string}

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <div>
              <Moment diff="2015-04-19">1976-04-19T12:59-0500</Moment>
              <Moment diff="2015-04-19" unit="days">1976-04-19T12:59-0500</Moment>
              <Moment diff="2015-04-19" unit="years" decimal>1976-04-19T12:59-0500</Moment>
            </div>
        );
    }
}

Duration

duration={string}

date={string}

Shows the duration (elapsed time) between two dates. duration property should be behind date property time-wise.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment duration="2018-11-1T10:59-0500"
                    date="2018-11-1T12:59-0500"
            />
        );
    }
}

Duration From Now

durationFromNow={bool}

Shows the duration (elapsed time) between now and the provided datetime.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment date="2018-11-1T12:59-0500"
                    durationFromNow
            />
        );
    }
}

Unix Timestamps

unix={bool}

Tells Moment to parse the given date value as a unix timestamp.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        const unixTimestamp = 198784740;
        return (
            <Moment unix>{unixTimestamp}</Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>

Local

local={bool}

Outputs the result in local time.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment local>
                2018-11-01T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time>Thu Nov 01 2018 18:59:00 GMT+0100</time>

Timezone

tz={string}

Sets the timezone. To enable server side rendering (SSR), client and server has to provide same datetime, based on common Timezone. The tz attribute will enable set the common timezone.

import React  from 'react';
import Moment from 'react-moment';
import 'moment-timezone';

export default class MyComponent extends React.Component {
    render() {
        const unixTimestamp = 198784740;
        return (
            <Moment unix tz="America/Los_Angeles">
                {unixTimestamp}
            </Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 09:59:00 GMT-0800</time>

Calendar

calendar={object|bool}

Customize the strings used for the calendar function.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        const calendarStrings = {
            lastDay : '[Yesterday at] LT',
            sameDay : '[Today at] LT',
            nextDay : '[Tomorrow at] LT',
            lastWeek : '[last] dddd [at] LT',
            nextWeek : 'dddd [at] LT',
            sameElse : 'L'
        };

        return (
            <Moment calendar={calendarStrings}>
                '1976-04-19T12:59-0500'
            </Moment>
        );
    }
}

Locale

locale={string}

Sets the locale used to display the date.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        const dateToFormat = '1976-04-19T12:59-0500';
        return (
            <Moment locale="de">{dateToFormat}</Moment>
        );
    }
}

Note In some cases the language file is not automatically loaded by moment, and it must be manually loaded. For example, to use the French locale, add the following to your bootstrap (e.g. index.js) script.

import 'moment/locale/fr';

Element

element={string|React.Component}

The element type to render as (string or function).

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment element="span">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<span>Mon Apr 19 1976 12:59:00 GMT-0500</span>

OnChange

onChange={func}

The onChange prop is called each time the date is updated, which by default is every 60 seconds. The function receives the new date value.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment onChange={(val) => { console.log(val); }}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Other Props

Any other properties are passed to the <time> element.

import React  from 'react';
import Moment from 'react-moment';

export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment className="datetime" aria-hidden={true}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time class="datetime" aria-hidden="true">Mon Apr 19 1976 12:59:00 GMT-0500</time>

Pooled Timer

By default a timer is created for each mounted <Moment /> instance to update the date value, which is fine when you only have a few instances on the page. However, performance can take a hit when you have many mounted instance. The problem is solved by using a pooled timer.

When pooled timing is enabled, react-moment will only use a single timer to update all mounted <Moment /> instances. Pooled timing is enabled by calling startPooledTimer() and stopped by calling clearPooledTimer().

Call the startPooledTimer() static method from your bootstrapping script (usually index.js) to initialize the timer.

import React from 'react';
import ReactDOM from 'react-dom';
import Moment from 'react-moment';
import App from './components/app';

// Start the pooled timer which runs every 60 seconds
// (60000 milliseconds) by default.
Moment.startPooledTimer();

// Or set the update interval. This will update the mounted
// instances every 30 seconds.
// Moment.startPooledTimer(30000);

ReactDOM.render(<App />, document.getElementById('mount'));

Note: The interval prop set on each <Moment /> instance is ignored when using pooled timing, except where interval={0} to disable updating.

Note: The startPooledTimer() method must be called before any <Moment /> instances are mounted.

Global Config

Some prop values may be set globally so you don't have to set them on every react-moment instance.

  • globalMoment
  • globalLocale
  • globalFormat
  • globalParse
  • globalFilter
  • globalElement
  • globalTimezone
  • globalLocal
import React  from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment/min/moment-with-locales';
import Moment from 'react-moment';

// Sets the moment instance to use.
Moment.globalMoment = moment;

// Set the locale for every react-moment instance to French.
Moment.globalLocale = 'fr';

// Set the output format for every react-moment instance.
Moment.globalFormat = 'D MMM YYYY';

// Set the timezone for every instance.
Moment.globalTimezone = 'America/Los_Angeles';

// Set the output timezone for local for every instance.
Moment.globalLocal = true;

// Use a <span> tag for every react-moment instance.
Moment.globalElement = 'span';

// Upper case all rendered dates.
Moment.globalFilter = (d) => {
    return d.toUpperCase();
};

const App = () => (
    <Moment>1976-04-19T12:59-0500</Moment>
);

ReactDOM.render(<App />, document.getElementById('mount'));

You can override the global values on a per-instance basis using regular props.

import React  from 'react';
import ReactDOM from 'react-dom';
import Moment from 'react-moment';

// Set the locale for every react-moment instance to French.
Moment.globalLocale = 'fr';

const App = () => (
    <div>
        {/*
            Renders using the 'fr' locale due to the global setting.
        */}
        <Moment>1976-04-19T12:59-0500</Moment>

        {/*
            Overrides the global locale and uses 'en' instead.
        */}
        <Moment locale="en">1976-04-19T12:59-0500</Moment>
    </div>
);

ReactDOM.render(<App />, document.getElementById('mount'));

Usage with React Native

If you are using React Native then you'll have to pass in Text.

import Moment from 'react-moment';
import { Text } from 'react-native';

Then:

<Moment element={Text} >1976-04-19T12:59-0500</Moment>

License

This software is released under the MIT license. See LICENSE for more details.

Contributors

react-moment's People

Contributors

ali-master avatar angelalexqc avatar beniaminrychter avatar centrual avatar dependabot[bot] avatar doctorhowser avatar etairi avatar firoxer avatar headzoo avatar idangozlan avatar jamesjryan avatar joefatora avatar khell avatar markacola avatar mrpbennett avatar nclavaud avatar pascalnegwer avatar pedrosimeao-7egend avatar sergiocruz avatar tadeo avatar tczhao avatar trevorr avatar tujoworker avatar tulak 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

react-moment's Issues

Cant find module error

bundle has warnings:
./~/moment/src/lib/locale/locales.js
Module not found: Error: Can't resolve './locale

Timezone feature is missing

Timezone feature will assist figure out server side rendering breaking.
Right now, if server and client are not synced, server side rendering is broken.

The solution is to add a feature of specific client time zone for parsing the timestamps.

Formatting throws an error

Whenever I try to format a date, an error is thrown:
TypeError: TypeError: this.localeData(...).postformat is not a function.

This happens whenever I use format in the JSX element, or set global format like Moment.globalFormat = 'MM-DD HH:mm'

Any idea what might be causing it? Not specifying a format or not setting globalFormat doesn't throw the error.

Diff format feature request

Feature Request

Would be nice if we could have a format option that is like units but can do a few units at all once. ie 3m40s vs 3.66 minutes.

Missing Type Definitions

Looks like subtract and add are missing from the TypeScript definitions file.

So these features cant be used in a TS project without throwing errors.

(Great project BTW, appreciate the work)

Locale attribute not change language

Hi.
Im setting locale to 'pt-br' and result is.
image

The language not change.
This is my code....
<Moment locale="pt-br">{project.lastModified}</Moment>

I doing something wrong?

Using locale yields an error

Example:

import React from 'react'
import Moment from 'react-moment';
import 'moment/locale/fi';

export default class MyHeader extends React.Component {
  render() {
    const dateToFormat = '1976-04-19T12:59-0500';
    return (<div>
         <Moment locale="fi">{dateToFormat}</Moment>
      </div>);
  }
}

Yields an error:

ncaught TypeError: Cannot read property 'preparse' of null
    at prepareConfig (from-anything.js?ede6:43)
    at createFromConfig (from-anything.js?ede6:22)
    at createLocalOrUTC (from-anything.js?ede6:109)
    at createLocal (local.js?8ec1:4)
    at hooks (hooks.js?38d9:6)
    at Function.value (index.js?948d:1)
    at t.value (index.js?948d:1)
    at t.value (index.js?948d:1)
    at eval (ReactCompositeComponent.js:347)
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)

No errors if I leave out the locale.

For the webpack config I'm using this definition to avoid the error

Module not found: Error: Can't resolve './locale'

locale props return error

Hi guys,

locale="fr" return this error :

TypeError: config._locale is null

<Moment format="D MMM YYYY" locale="fr">{article.dateCreated.toISOString().substring(0, 10)}</Moment>

Without locale="fr", i've no error :(

Couldn't find preset "es2015" realtive to directory

I get this error after installing react-moment and importing it into my react-native project

TransformError: ../node_modules/react-moment/dist/index.js: Couldn't find preset "es2015" realtive to directory "../node_modules/react-moment"

How to use react-moment with millisecods

Thanks guys for such a great module.

I need to ask, how can i use react-moment with milliseconds instead of timestamps.
for example when i use
<Moment interval={20000} fromNow element={Text} unix>1517895695215</Moment>

i get in 48052 years., instead it should return 7hours (as of writing this question)

Dist version bundles moment

Despite moment being required as a peer dependency, this module will always bundle it's own version of moment when included via webpack etc. Though I don't think it would end up being used, moment is fairly large and bloats the bundle size.

I haven't tested this out for sure, but I'm guessing moment is being required through moment-timezone, so you need to add moment-timezone as a peer dependency, and to the webpack externals configuration to prevent it being bundled.

Update component after some time when using fromNow

The component doesn't currently have a mechanism to update the time automatically when out of date, i.e.

import React  from 'react'
import Moment from 'react-moment'

export default () => (
  <Moment fromNow>{new Date()}</Moment>
)

outputs:

<time>a few seconds ago</time>

and the content will not update over time (in a minute it will still display "a few seconds ago").

Would you accept a pull request that adds support for this?

Style React-Native element

I see that I am supposed to provide a class type like 'Text' to the element prop in React-Native. This works but I cannot figure out how to style that element because I am can just pass the class as a type and Moment does not have a 'style' prop for forwarding. How should I do this?

Element are not removed from pooledElements

When component is unmount, it is not remove from pooledElements array.

I suggest something like add (not tested):

static removePooledElement(element) { const index = Moment.pooledElements.indexOf(element); if (index !== -1) { Moment.pooledElements.splice(index, 1); } }

and on:
clearTimer = () => { if (!Moment.pooledTimer && this.timer) { clearInterval(this.timer); this.timer = null; } if (Moment.pooledTimer && this.timer) { Moment.removePooledElement(this); } };

Error: Expected a component class, got [object Object].

React-Native project. Trying to display story.date_created, such as 2017-02-24T08:00:00.000Z

import Moment from 'react-moment';
...
let dateToFormat = new Date(story.date_created);
return(
...
<View>
     <Moment date={dateToFormat} />
     <Text style={styles.author}>{story.given_name.toUpperCase() + ' ' + story.family_name.toUpperCase()}</Text>
</View>
...
)

React: 16.0.0-alpha.12
React-Native: 0.45.0
React-Moment: 0.2.4

Support for local property

Hi, this component does not seem to have support for the standard moment is "local" property. Is there a way to achieve the following using your component?

var now = moment.utc('2017-10-06T17:27:57').local().
format();

current time starts from 5 minutes

I have used moment in the react project, but as it was supposed to show the time from a second it started showing time from 5 minutes but it was supposed to show a second ago.
here is my code:
<Moment fromNow ago>{new Date(e.created_at)}</Moment> &nbsp; ago
can anyone suggest what I am doing wrong or is it this libraries problem?

Add or substract?

Hello,

First of all, thanks for this lib!

I wonder how can I add or substract days/hours from current date?

Thanks

FromNow/ToNow omitting ago

Hi,

I found some strange behavior which results in wrong output when using FromNow/ToNow including ago to omit the ago suffix. If I don't omit the ago, it displays both "in x days" and "x days ago" when using ToNow. So why do we have both FromNow and ToNow if both doing the same but indicating they're just doing it in one direction? If I omit the prefix it only displays absolut numbers without saying if it is "in x days" or "x days ago" so it may be either one or the other - I simply don't know. To make sure to display that without using a prefix, the number must be positive when having "in x days" and negative when having "x days ago".

Hope you understand my problem
Thanks in advance!

typings: Missing dependency react-native

The index.d.ts file references the react-native module but this module is not listed as a dependency.

Maybe we could use

import { CSSProperties } from "react";
// ...
style?: CSSProperties,

instead of

import { ViewStyle } from 'react-native';
// ...
style?: ViewStyle,

since react is already listed as a dependency?

Missing a way to change the language

You should add a way to change the language of the time strings. Probably a prop in the static function "getDatetime" used to: datetime.locale(prop.locale) before returning.
Something like that:

static getDatetime(props) {
        let {
            date,
            parse,
            utc,
            unix,
            tz,
            locale
        } = props
        date = date || props.children

        let datetime = null

        if (utc) {
            datetime = moment.utc(date, parse)
        } else if (unix) {
            datetime = moment.unix(date)
        } else {
            datetime = moment(date, parse)
        }
        if (tz) {
            datetime = datetime.tz(tz)
        }
        datetime.locale(locale ? locale : (window.navigator.userLanguage || window.navigator.language))

        return datetime
    }

npm WARN [email protected] requires a peer of react@^15.0.0 but none was installed.

Above warning shows when I try to run
npm install --save moment moment-timezone react-moment
in my react-native project. I also can not use (import) moment
What is the problem here ? Am I doing something wrong ?

In my package.json file

"dependencies": {
"moment": "^2.18.1",
"moment-timezone": "^0.5.13",
"react": "16.0.0-alpha.12",
"react-moment": "^0.2.4",
"react-native": "0.45.1",
}

moment().from() / moment.to() Boolean parameter

Hey, first of all thanks for this great package! :)

I can't seem to figure out how to pass the optional Boolean parameter to the from and to properties, which allows for disabling the "in" or "ago" text and just gives the time from/to eg. "5 Years" vs "5 Years ago".

example from moment's documentation end.from(start, true); // "5 days"

Is this possible after all?

Thanks
Daniel

Content does not update when props are updated

My use-case consists of a container component passing state as props to a <Moment /> component.

I noticed the content (displayed date) is not updated when the new props have been received. I have to wait until the next interval callback is triggered to see the content update.

Will submit a PR.

Moment.startPooledTimer and FromNow doesn't work fine

Hi all,

I get errors when I try to use Moment.startPooledTimer.

In my index.js:
Moment.startPooledTimer(3000);

In my component:
<Moment fromNow>{new Date(this.props.mission.deadline).toISOString()}</Moment>

And the error on my js console:

index.js:1 Uncaught TypeError: Cannot read property 'fromNow' of undefined
    at t.value (index.js:1)
    at index.js:1
    at Array.forEach (<anonymous>)
    at index.js:1

Any idea?

Format to Uppercase

Hey there,
is it possible to manipulate the output after it has been parsed by moment? I am using react-moment with react-native and would like to display the date in Uppercase. Unfortunately I can't use CSS for it but have to use JavaScript .toUpperCase() method.

Couldn't find a way to manipulate the output beside the Format Parameter which doesn't help in this case.

Typescript Typings

Hello,

I wrote this typescript typings:

declare module 'react-moment' {
    import moment from 'moment';
    import {Component} from "react";

    type addOrSubtrack = {
        years?: number,
        y?: number
        quarters?: number,
        Q?: number,
        months?: number,
        M?: number,
        weeks?: number,
        w?: number,
        days?: number,
        d?: number,
        hours?: number,
        h?: number,
        minutes?: number,
        m?: number,
        seconds?: number,
        s?: number,
        milliseconds?: number,
        ms?: number
    }

    type dateTypes = string|number|Array<string|number|object>|object;
    type calendarTypes = boolean|object;

    type MomentProps = {
        element?: JSX.Element,
        date?: dateTypes,
        parse?: string|Array<string>,
        format?: string,
        add?: addOrSubtrack,
        subtract?: addOrSubtrack,
        ago?: boolean,
        fromNow?: boolean,
        fromNowDuring?: number,
        from?: dateTypes,
        toNow?: boolean,
        to?: dateTypes,
        calendar?: calendarTypes,
        unix?: boolean,
        utc?: boolean,
        tz?: string,
        locale?: string,
        interval?: number,
        diff?: dateTypes,
        unit?: string,
        decimal?: boolean,
        filter?: Function,
        onChange?: Function

    }

    export default class Moment extends Component<MomentProps, any> {
        constructor(props:MomentProps);
        public static globalMoment: moment.Moment;
        public static globalLocale: string;
        public static globalFormat: string;
        public static globalParse: string;
        public static globalTimezone: string;
        public static globalElement: string;
        public static globalFilter: Function;
        public static startPooledTimer(interval?: number): void;
        public static clearPooledTimer(): void;
        public static getDatetime(props: MomentProps): any;
    }
}

Have a great day!

Node has not been attached to a view

Getting the following error "Node has not been attached to a view" here is my code
Lastest react native version

<View style={styles.headerView}>
                    <Text style={styles.headerText}>{this.props.title}</Text>
                    {photoDate != null &&
                    <Text style={styles.headerDateText}>
                        <Moment parse="YYYY-MM-DD HH:mm">
                            1976-04-19 12:59
                        </Moment>
                    </Text>
                    }
                </View>

Interval doesn't seem to do anything

I'm using react-moment in a web page, and while it displays correctly with no errors, it is not updating. Here is the code I'm using:

`import React, { Component } from 'react';
import Moment from 'react-moment';

export default class Clock extends Component {

render(){
    const displayTime = new Date();
    return(
        <Moment interval={1000} format={this.props.format}>
            {displayTime}
        </Moment>
    );
}

}
`

This component is called by the following line from another page:
<Clock fromat="yyyy MMM dd HH:mm:ss"/>

I'm using the latest version of react from npm.

is this possible with react moment?

Trying to write the equivalent of this line in react for demo data to be used with react highcharts. Not sure if it's possible or what the correct syntax is.

for (var i = 30; i >= 1; i--) {
thisBillingPeriod.push([moment().date(15).subtract(i,'days').valueOf(),(Math.random() * 30) + 80]);
}

I've tried similar variations below but no luck:

const demoDate = new Date();
for (var i = 30; i >= 1; i--) {
thisBillingPeriod.push([<Moment subtract={{days: 1}}>{demoDate},(Math.random() * 30) + 80]);
}

globalLocale doesn't change the language

Why Moment.globalLocale from react-moment doesn't change the locale and translate the language?

image

I fixed this just with moment but not with react-moment

import React, {Component} from 'react'
// import Moment from "react-moment"
// import moment from "moment"
import moment from 'moment/min/moment-with-locales'
import {Text, View} from "react-native"

export default class ParseDate extends Component {
    constructor(props) {
        super(props)

        // Set the locale for every moment instance to Portuguese.
        moment.locale('pt-br')
        this.localMoment = moment()
    }

    render() {
        return (
            <View>
                {/*<Moment element={Text} format={`LLL`}>{new Date().toString()}</Moment>*/}
                <Text>{this.localMoment.format('LLLL')}</Text>
            </View>
        )
    }
}

output: Quinta-feira, 9 de novembro de 2017 às 02:07

image

What's going on with react-moment locale?

References: #10 #17 #41
https://github.com/headzoo/react-moment#global-config
https://github.com/headzoo/react-moment#usage-with-react-native

Consider pooled updates

The current design creates a separate timer for each individual component. If the component is used many times on a single page, it can create quite a few timers. It might be better to pull the setInterval out of the component and maintain an update function list that an external interval timer iterates over.

Cannot parse datetime

I have the following date:
"2017-05-16T22:00:00Z"
and use this to parse it:

<Moment tz="Europe/Berlin" locale="de" parse="YYYY-MM-DD HH:mm:ss" >
    { value }
</Moment>)

however invalid date is returned. Any suggestions?

Test suite fails when current UTC offset is not -0500

Hi,

Running the test suite here fails:

 FAIL  tests/index.js
  react-moment
    ✕ children (34ms)
    ✕ date (6ms)
    ✕ parse (3ms)
    ✓ format (3ms)
    ✓ fromNow (10ms)
    ✓ from (10ms)
    ✓ toNow (10ms)
    ✓ to (10ms)
    ✓ calendar (3ms)
    ✕ unix (3ms)
    ✓ utc (4ms)
    ✓ other (4ms)

  ● react-moment › children

    expect(received).toEqual(expected)
    
    Expected value to equal:
      "Mon Apr 19 1976 12:59:00 GMT-0500"
    Received:
      "Mon Apr 19 1976 17:59:00 GMT+0000"
      
      at Object.<anonymous> (tests/index.js:26:91)

  ● react-moment › date

    expect(received).toEqual(expected)
    
    Expected value to equal:
      "Mon Apr 19 1976 12:59:00 GMT-0500"
    Received:
      "Mon Apr 19 1976 17:59:00 GMT+0000"
      
      at Object.<anonymous> (tests/index.js:44:91)

  ● react-moment › parse

    expect(received).toEqual(expected)
    
    Expected value to equal:
      "Mon Apr 19 1976 12:59:00 GMT-0500"
    Received:
      "Mon Apr 19 1976 12:59:00 GMT+0000"
      
      at Object.<anonymous> (tests/index.js:56:91)

  ● react-moment › unix

    expect(received).toEqual(expected)
    
    Expected value to equal:
      "Mon Apr 19 1976 12:59:00 GMT-0500"
    Received:
      "Mon Apr 19 1976 17:59:00 GMT+0000"
      
      at Object.<anonymous> (tests/index.js:134:91)

Test Summary
 › Ran all tests.
 › 4 tests failed, 8 tests passed (12 total in 1 test suite, run time 1.077s)

I guess this has something to do with the UTC offset, either the parsing or the formatting.

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.