首页 > 解决方案 > 如何在momentjs中将开始时间设置为特定时间

问题描述

我正在尝试将一天的开始时间设置为特定时间。目前,在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

标签: javascriptdatetimemomentjs

解决方案


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

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>


推荐阅读