【问题标题】:How to format JSON dates with JavaScript?如何使用 JavaScript 格式化 JSON 日期?
【发布时间】:2021-12-15 18:12:09
【问题描述】:

我有一个 HTML <input type="date" name="departing" />,它返回例如以下格式的日期:2021-11-07

当我将此变量转发到我的车把时,它显示如下:

Mon Nov 08 2021 01:00:00 GMT+0100 (Central European Standard Time)

我想让它显示为:

07/11/2021

我尝试使用 date-fns 对其进行格式化,如下所示:

departing = format(parseISO(departing.getDate()), "dd/MM/yyyy");

然后我的车把显示:"Invalid Date"

我很困惑。关于如何让该日期显示在 07/11/2021 中的任何想法 格式?

【问题讨论】:

    标签: javascript date-fns


    【解决方案1】:

    首先创建一个日期对象

    const newDate = new Date();
    

    现在你可以操纵代码来获得任何你想要的答案

    var outputDate = newDate .getDate() + "/" +  (newDate.getMonth()+1) + "/" + 
    newDate.getFullYear();
    

    输出将类似于 2021 年 1 月 11 日

    【讨论】:

      【解决方案2】:

      您可以简单地分别使用#getDate()、#getMonth() 和#getFullYear() 方法,然后按照您想要的顺序显示它们:

      const date = new Date(departing);
      const day = date.getDate();
      const month = date.getMonth() + 1;
      const year = date.getFullYear();
      
      console.log(`${day}/${month}/${year}`);
      

      希望它能回答问题。

      【讨论】:

        【解决方案3】:

        你可以通过多种方式做到这一点

        方法一:-

        let n = new Date()
        console.log(n.toLocaleDateString("en-US")
        output=== 31/9/2021
        

        方法 2 :- 获取单独的值并合并

        let n = new Date()
        console.log(n.getDate()+"/"+n.getMonth()+"/"+n.getFullYear())
        output=== 31/9/2021
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-18
          • 1970-01-01
          • 2022-01-18
          相关资源
          最近更新 更多