首页 > 解决方案 > 将时间戳转换为日期和时间(带时区)的任何解决方案?在 React.js 中

问题描述

我试图构建一个日历组件,但在我的后端 Jason Api 上,日期以时间戳给出。那么我将如何将时间戳转换为日期和时间(带时区)?

考虑下面的代码。

const appointments = [
  {
    id: 0,
    title: 'Watercolor Landscape',
    startDate: new Intl.DateTimeFormat('en-US').format(1585640511000), // here to convert timestamp 
    endDate: new Date(2018, 6, 23, 11, 30),
    ownerId: 1,
  }
];
constructor(props) {
    super(props);

    this.state = {
      data: appointments,
    };

    this.commitChanges = this.commitChanges.bind(this);
  }

render() {
    const { data } = this.state;
    console.log( data) // I console the data 
    return (
      <Paper>
        <Scheduler
          data={data}
        >
   )
}

这是我控制台的结果:

在此处输入图像描述

我的问题是如何将 startDate 的类型转换为与 endDate 相同的类型?

标签: reactjsdatetimestampformat

解决方案


你可以使用moment.js。它提供了一种将字符串解析为 Date 对象的简单方法。

var date = moment("3/31/2020", "M/DD/YYYY");

推荐阅读