首页 > 编程知识 正文

Ant Design Table 时间格式化教程

时间:2023-11-20 16:04:52 阅读:293389 作者:AQUW

这篇文章将教你如何在 Ant Design Table 中进行时间格式化。

一、格式化时间为固定格式

Ant Design Table 中的时间字段默认展示的格式为:YYYY-MM-DD HH:mm:ss,如果你需要将这个格式改为自定义的格式,可以使用 moment.js 库。具体步骤如下:

// 引入 moment.js 库
import moment from 'moment';

// 定义 render 函数
const renderTime = (text) => {
  const formatTime = moment(text).format('YYYY年MM月DD日 HH:mm:ss');
  return {formatTime};
};

// 在 columns 中使用 render 函数
const columns = [
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    render: renderTime,
  },
  ...
];

上述代码中,我们首先引入了 moment.js 库,然后在 renderTime 函数中使用 moment(text) 将传入的时间字符串转换为 moment 对象,最后使用 format 方法按照指定的格式输出。

二、根据特定条件进行时间格式化

有时候我们需要根据特定条件来进行时间的格式化,例如:若时间距离当前时间不到一小时,则显示“刚刚”;若距离当前时间不到一天,则显示“X小时前”;否则显示“X天前”。

实现这个功能的代码如下:

const renderTime = (text) => {
  const time = moment(text);
  const diff = moment().diff(time, 'minutes'); // 计算时间差

  let formatTime = '';
  if (diff < 60) {
    formatTime = '刚刚';
  } else if (diff < 1440) {
    formatTime = `${Math.floor(diff / 60)}小时前`;
  } else {
    formatTime = `${Math.floor(diff / 1440)}天前`;
  }

  return {formatTime};
};

在上述代码中,我们使用 moment().diff(time, 'minutes') 函数来计算当前时间和传入的时间之间的时间差,以分钟为单位。

三、处理时间戳

有时候我们的后端接口会返回时间戳(以毫秒为单位),此时我们需要将它转换为日期格式并进行格式化。

实现这个功能的代码如下:

const renderTime = (text) => {
  const time = moment(parseInt(text) * 1000);
  const formatTime = time.format('YYYY年MM月DD日 HH:mm:ss');
  return {formatTime};
};

上述代码中,我们首先使用 parseInt 函数将传入的字符串转换为数字(若传入的是数字,则不用转换),然后乘以1000转换为毫秒级别的时间戳。之后使用 moment(time) 将转换后的时间戳转换为 moment 对象,然后再使用 format 函数按照指定的格式输出。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。