Reputation: 1045
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:
2:00 pm
.Yesterday
.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
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