【问题标题】:How can I format time using moment.js in React JS and webpack如何在 React JS 和 webpack 中使用 moment.js 格式化时间
【发布时间】:2019-10-22 11:42:43
【问题描述】:

我在我的 React 应用程序中使用 moment JS 来格式化日期,这不是使用 create-react-app 设置的。我想将时间戳格式化为如下可读格式:

  1. 如果提供的时间戳是今天的,它应该只显示时间。例如: 2:00 pm
  2. 如果提供的时间戳是昨天的,它应该显示昨天没有时间。例如: Yesterday
  3. 如果提供的时间戳是昨天之前的任何时间,它应该显示 没有时间的确切日期。例如:24 Feb, 2019

到目前为止我的代码: 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;

【问题讨论】:

标签: javascript reactjs webpack momentjs


【解决方案1】:

使用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);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"&gt;&lt;/script&gt;

在此处阅读更多信息https://momentjs.com/docs/#/durations/humanize/

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多