Search code examples
javascripttypescriptreact-nativemomentjsmoment-timezone

moment.fromNow() timezone issue


I am getting post of news from server with date that doesnt includes timezone, i know that posts is from EST time zone, example : March 30, 2020 at 10:53 AM (-5 GMT); When post was just updated like few seconds ago moment.fromNow() showing me it was posted like 8 hours ago becasue i am living in +3 GMT. What should i do so that moment.fromNow() showing right time posts was updated without taking difference in time zones. Sorry for my english. My code:

...
const dateMoment = moment(date, 'MMMM DD, YYYY h:mm A');
news.date = dateMoment.toDate();
...

//in component

<Text style={styles.cardDate}> {moment(news.date).fromNow()} </Text> //getting text '8 hours ago' even if it was posted right now 
...

 {moment(news.date).tz('America/New_York').fromNow()} // didn't work too, still 8 hours difference

Solution

  • It was my mistake. I parsed date wrong. The right way was :

    const dateMoment = moment(date, 'MMMM DD, YYYY h:mm A').tz('America/New_York', true);
    news.date = dateMoment.toDate();
    

    I should have set keepLocalTime to true in tz(timezone: string, keepLocalTime?: boolean): moment.Moment.

    Now i just use in component:

    <Text style={styles.cardDate}> {moment(news.date).fromNow()} </Text>
    

    And actualy timezone was wrong too, it's not New York it's LA...