1

Hi i need to convert timestamp to something like Minutes/Hours/Days ago. I am using moment .But as these are j-query plugins so i am feeling challenges in executing that in react.

I have often heard that it is not recommended to use j-query with react.Or is there any other way to sort things out without using j-query

  • This question is beneficial for those who don't want to add j-query plugins in react.I have searched on the moment official documentation too but there was no clear example on how to use timestamp with moment. –  Sep 04 '19 at 08:31

2 Answers2

4

To use moment.js in react.

1) Install moment.js package npm install moment --save

2) Import moment in your React component

import moment from 'moment'

Convert your timestamp (miliseconds) to date using new Date(1567485137) and use fromNow method of moment js.

moment(new Date(timestamp in milisecond).fromNow()

If you want to values as only days ago you can use from method

moment(new Date(timestamp in milisecond)).from(new Date())

Using react-moment

If you are using react-moment then use Moment component as below:

import Moment from "react-moment";

then use as below

<Moment fromNow date={new Date(timestamp in milisecond).toJSON()} />
Juned Lanja
  • 1,466
  • 10
  • 21
  • import Moment from 'react-moment'; Am i importing the right thing ? –  Sep 04 '19 at 05:45
  • it is returning 50 years ago –  Sep 04 '19 at 05:59
  • 1567485137 is second or milisecond ? – Juned Lanja Sep 04 '19 at 06:02
  • it is in seconds. –  Sep 04 '19 at 06:14
  • what should be expected output? – Juned Lanja Sep 04 '19 at 06:16
  • Janed thankyou for helping but i am not getting the desired result.So let me clear you whole scenario. My timestamp is in seconds whose value is 1567557135 and you can check on https://www.epochconverter.com/ that it's relative 6 hours ago. I want to display that thing only. for lesser than hour it show seconds ago and then less than day it should show hours ago and then after days ago.This is the whole thing. –  Sep 04 '19 at 06:44
  • Obviously as your converting seconds to milliseconds 1567485137 * 100. you need to figure out time in milliseconds by your own. Give timestamp data as millisecond and it will work. – Juned Lanja Sep 04 '19 at 06:57
  • it is working fine for {moment(new Date(1567485137000 )).fromNow()} . I have converted seconds to miliseconds. –  Sep 04 '19 at 06:57
0

You can convert your timestamp to Date as described in this answer with Moment.Js. Since you do not have the timezone adjustment, you can simply convert it as shown below.

var t = new Date( 1370001284000 );
var formatted = t.format("dd.mm.yyyy hh:MM:ss");

After converting it you can find the difference by calculatedDate.FromNow() method using Moment.Js.

Hasan
  • 1,243
  • 12
  • 27