【问题标题】:How to set start day time to particular time in momentjs如何在momentjs中将开始时间设置为特定时间
【发布时间】:2021-10-07 11:45:06
【问题描述】:

我正在尝试将一天的开始时间设置为特定时间。目前,在momentjs中,我可以像这样获得startOf day

 let now = moment()
 console.log('now', now.toString()) 
 console.log('start Day', now.startOf('day').toString()) // Thu Oct 07 2021 00:00:00 GMT+0530
 console.log('end day', now.endOf('day').toString()) //Thu Oct 07 2021 23:59:59 GMT+0530

有什么方法可以让我设置我的一天从特定时间开始,就像我想开始我的一天一样

2021 年 10 月 7 日星期四 08:00:00 GMT+0530

然后结束

2021 年 10 月 7 日星期四 07:59:59 GMT+0530

【问题讨论】:

    标签: javascript datetime momentjs


    【解决方案1】:

    您可能应该编写自己的函数来实现这一点。

    function customStartOf(momentObj) {
      return momentObj.clone().startOf('day').hours(8);
    }
    
    function customEndOf(momentObj) {
      // I assume that end of the day is bigger than start of the day
      return momentObj.clone().endOf('day').add(1, 'days').hours(7);
    }
    
    let now = moment();
    
    console.log('now', now.toString()) ;
    console.log('start Day', now.startOf('day').toString());
    console.log('end day', now.endOf('day').toString());
    
    console.log('custom start Day', customStartOf(now).toString());
    console.log('custom end day', customEndOf(now).toString());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    【讨论】:

    • 我想要 "Thu Oct 07 2021 08:00:00 GMT+0530" 到 "Fri Oct 08 08:00:00 GMT+0530" == 1 之间的区别,但我确实明白了根据您的逻辑,知道如何实现这一目标
    • 我想根据“startOf day”计算两天的日期差
    • console.log('now', now.toString()) ; 打印相同的值,就像这个打印的 console.log('custom end day', customEndOf(now).toString());
    • @ManjeetThakur 我编辑了我的答案。自定义函数现在返回克隆对象,因此add 函数不会更改自定义函数结果。
    • 但是 console.log('custom start Day', customStartOf(now).startOf('day').toString()) 仍然打印Thu Oct 07 2021 00:00:00 GMT+0530
    猜你喜欢
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多