首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript:计算今天和特定工作日之间的时间

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

Stack Overflow用户
提问于 2017-08-07 08:01:11
回答 2查看 240关注 0票数 3

我正在寻找一种方法来计算从现在UTC-7到下个星期六(独立于日期进行计算)在特定的UTC-7时间(08:00)在Javascript之间的时间(秒)。

目前我正在使用这个代码,但是我想用上面提到的计算方法来代替给出具体的日期:

代码语言: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

EN

回答 2

Stack Overflow用户

发布于 2017-08-07 08:25:24

为简单起见,您可以使用MomentJS动态计算出下一个Saturday和下一个Saturday的日期。

要为即将到来的Saturday实例化一个Moment日期,可以通过.day(int)应用编程接口来实现。例如,.day(6)

要获得epoch时间,您可以执行.unix(),但这里有一个问题。默认情况下,它返回的是从epoch开始的seconds,而不是标准毫秒。

示例:

代码语言:javascript
复制
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);
代码语言:javascript
复制
<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>

参考:

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

票数 1
EN

Stack Overflow用户

发布于 2017-08-07 09:04:24

在POJS中,(单向的)你可以在特定的时间获得下一个星期六,如下所示。

代码语言:javascript
复制
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());

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45537782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档