mevrick
mevrick

Reputation: 1045

How can I format time using moment.js in React JS and webpack

I am using the moment JS to format dates in my React app which is NOT setup using create-react-app. I want to format the timestamp to a readable format like below:

  1. If the timestamp supplied is for today it should show only show the time. eg: 2:00 pm.
  2. If the timestamp supplied is for yesterday it should show yesterday without time. eg: Yesterday.
  3. If the timestamp supplied is anytime before yesterday it should show the exact date without time. eg: 24 Feb, 2019.

Code I have so far: webpack.config.js:-

    const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
....
plugins: [
     new MomentLocalesPlugin({
         localesToKeep: ['es-us', 'hi']
     })
]

App.js

import React, { useEffect } from 'react';
import moment from 'moment';

const App = () => {
    const timestamp = '1571744305';
    return (
        <Router>
            <div>
               {moment(timestamp).calendar()}//08/21/2019
            </div>
    );
};

export default App;

Upvotes: 0

Views: 462

Answers (1)

Yahiya
Yahiya

Reputation: 791

Using moment.js, you can do like this

let now = moment.duration().humanize();
let oneMin = moment.duration(1, "minutes").humanize(); // a minute
let twoMin = moment.duration(2, "minutes").humanize(); // 2 minutes
let hours = moment.duration(24, "hours").humanize();  // a 24 hours
let days = moment.duration(24, "days").humanize();  // a 24 days
let weeks = moment.duration(2, "weeks").humanize();  // a weeks
let months = moment.duration(5, "months").humanize();  // a months
let years = moment.duration(7, "years").humanize();  // a years

console.log(now);
console.log(oneMin);
console.log(twoMin);
console.log(hours);
console.log(days);
console.log(weeks);
console.log(months);
console.log(years);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>

Read more here https://momentjs.com/docs/#/durations/humanize/

Upvotes: 2

Related Questions