简体   繁体   English

如何在 React JS 和 webpack 中使用 moment.js 格式化时间

[英]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 .我正在使用时刻 JS 来格式化我的 React 应用程序中的日期,该应用程序不是使用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:00 pm
  2. If the timestamp supplied is for yesterday it should show yesterday without time.如果提供的时间戳是昨天的,它应该显示昨天没有时间。 eg: Yesterday .例如: Yesterday
  3. If the timestamp supplied is anytime before yesterday it should show the exact date without time.如果提供的时间戳是昨天之前的任何时间,它应该显示没有时间的确切日期。 eg: 24 Feb, 2019 .例如: 24 Feb, 2019

Code I have so far: webpack.config.js:-我到目前为止的代码:webpack.config.js:-

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

App.js应用程序.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;

Using moment.js, you can do like this使用 moment.js,你可以这样做

 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/在这里阅读更多https://momentjs.com/docs/#/durations/humanize/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM