Javascript:计算今天和特定的下一个工作日时间之间的时间

时间:2017-08-07 00:01:11

标签: javascript time

我正在寻找一种方法来计算UTC-7时间(08:00)在UTC-7和接下来的星期六之间的秒数(与计算日期无关)在Javascript中。

目前我正在使用此代码,但我想用上述计算替换给定的具体日期:

// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); currentDate.setHours(currentDate.getHours() - 7);

// Set some date in the future. 
var ClashDate  = new Date("August 6, 2017 16:40:00");
var BashDate  = new Date("August 12, 2017 08:00:00");

// Calculate the difference in seconds between the future and current date
var diffclash = ClashDate.getTime() / 1000 - currentDate.getTime() / 1000;
var diffbash = BashDate.getTime() / 1000 - currentDate.getTime() / 1000;

有人可以帮帮我吗?

您诚挚的 Yamper

2 个答案:

答案 0 :(得分:1)

为简单起见,您可以使用MomentJS动态确定以下Saturday的日期以及之后的下一个Saturday

要实现即将到来的Moment日期Saturday,您可以通过.day(int) API执行此操作。例如。 .day(6)

要获得epoch时间,你可以.unix(),但这里有一个问题。默认情况下,它会返回seconds epoch,因为var now = new Date(); var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); currentDate.setHours(currentDate.getHours() - 7); moment().tz("America/New_York").format(); // Set some date in the future. var ClashDate = moment().day("Saturday").hour(16).minutes(40).seconds(0); var BashDate = moment().day(13).hour(8).minutes(0).seconds(0); console.log("Next Saturday date is => " + ClashDate.toString()); console.log("Next Next Saturday date is => " + BashDate.toString()); // Calculate the difference in seconds between the future and current date var diffclash = ClashDate.unix() - currentDate.getTime() / 1000; var diffbash = BashDate.unix() - currentDate.getTime() / 1000; console.log("diffClash => " + diffclash); console.log("diffBash => " + diffbash);不是标准毫秒。

示例:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data.min.js"></script>
To use this feature, use the Messenger app

<强>参考:

MomentJS - https://momentjs.com/docs/

答案 1 :(得分:1)

在POJS中,(单程)你可以在特定的时间到达下一个星期六。

function nextSaturday(date) {
  const d = date ? new Date(date) : new Date();
  d.setDate(d.getDate() + (6 - d.getDay()) % 7);
  return new Date(`${d.toISOString().split('T').shift()}T14:00:00.000Z`);
}

console.log(nextSaturday('2017-08-13'));
console.log(nextSaturday('2017-08-31'));
console.log(nextSaturday());