【问题标题】:Get current date with fixed time string - moment js使用固定时间字符串获取当前日期 - 时刻 js
【发布时间】:2021-05-19 08:10:26
【问题描述】:

考虑到日期是 2021 年 5 月 19 日,我需要获取字符串为 2021-05-19T23:59:00.000Z

我尝试了 moment().format() 但它返回的是当前日期时间字符串。

我需要 formatString 中的时间为 23:59 以便总字符串变为 2021-05-19T23:59:00.000Z

知道如何实现这一目标吗?

【问题讨论】:

    标签: javascript momentjs


    【解决方案1】:

    您可以使用moment().endOf("day").format()

    console.log(moment().endOf("day").format());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    您可以使用纯 javascript 来做同样的事情。

    var end = new Date();
    end.setHours(23,59,59,999);
    

    【讨论】:

      【解决方案2】:

      可以使用endOf的方法:

      moment().endOf('day')
      

      并使用format 以获得您需要的确切格式:

      let t1 = new moment();
      console.log(t1.format());
      
      let t2 = t1.endOf('day');
      console.log(t2.format());
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

      【讨论】:

        【解决方案3】:

        你可以试试:

        var date = moment().format("YYYY-MM-DDT23:59:00.000[Z]");
        

        【讨论】:

          【解决方案4】:

          你可以使用 moment.js 中的 endOf() 方法:

          moment().endOf('day').format()
          

          要以当地时间打印时间,请尝试使用 toString()。

          let now = moment();
          console.log('end : ' + now.endOf('day').toString());
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-05-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-23
            • 1970-01-01
            • 2021-11-19
            • 1970-01-01
            相关资源
            最近更新 更多