代码之家  ›  专栏  ›  技术社区  ›  dot

Typescrpt-如何将json字符串日期表示形式转换为日期对象

  •  1
  • dot  · 技术社区  · 3 年前

    我有一个API调用,它返回一个json字符串数组。我需要更改显示格式-只需要月份和日期。

    我的逻辑有一个错误,因为它把八月翻译成“7”而不是“8”。此外,第一次记录的日期被解释为3天,而不是25天。

    这是数据外观的示例:

    [
    {"reportRefreshDate":"2021-08-25T07:18:06","Widgets":13,"Gizmos":6},{"reportRefreshDate":"2021-08-28T07:18:06","Widgets":1,"Gizmos":0},{"reportRefreshDate":"2021-08-29T07:18:06","Widgets":1,"Gizmos":0}
    ]
    

    密码

      const reportRefreshDate: string[] = [];
      const totalWidgets: number[] = [];
      const totalGizmos: number[] = [];
      const totalDooDads: number[] = [];
    
      for (const record of data) {
        const tempdate = new Date(record.reportRefreshDate);
    
        reportRefreshDate.push(tempdate.getMonth() + "/" + tempdate.getDay())
      }
    

    tempdate
    Wed Aug 25 2021 07:18:06 GMT-0400 (Eastern Daylight Time)
    
    tempdate.getMonth()
    7
    

    如果你能给我指出正确的方向,那就太好了。现在我也在查看Date的重载,看看我创建变量的方式是否不正确。

    编辑1

    我想我可以转换成localeDateString,然后去掉这一年?我注意到,当我使用toLocaleDateString()时,它会在调试控制台中返回正确的值:

    tempdate.toLocaleDateString()
    '8/25/2021'
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   Alan Zhou    3 年前

    你不应该使用 getDay() 函数,该函数将以从0开始的数字形式返回星期几。

    相反,您应该使用 getDate() 因此,您可能需要将代码重构为以下内容。

    reportRefreshDate.push(tempdate.getMonth() + "/" + tempdate.getDate())