Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在谷歌应用程序脚本中以mm.dd.yy格式获取每个即将到来的星期五的日期?_Javascript_Google Apps Script - Fatal编程技术网

Javascript 如何在谷歌应用程序脚本中以mm.dd.yy格式获取每个即将到来的星期五的日期?

Javascript 如何在谷歌应用程序脚本中以mm.dd.yy格式获取每个即将到来的星期五的日期?,javascript,google-apps-script,Javascript,Google Apps Script,我想为每个即将到来的星期五检索格式为mm.dd.yy的日期。假设今天是9月9日星期三。下一个即将到来的周五是9月11日或2020年11月9日。如何使用JavaScript编程此逻辑 var today = Utilities.formatDate(new Date(), "GMT+1", "mm.dd.yy") var next_friday = ? 任何指示都会有帮助 使用 console.log(Date.next().friday()) 您可以在

我想为每个即将到来的星期五检索格式为
mm.dd.yy
的日期。假设今天是9月9日星期三。下一个即将到来的周五是9月11日或2020年11月9日。如何使用JavaScript编程此逻辑

var today = Utilities.formatDate(new Date(), "GMT+1", "mm.dd.yy")
var next_friday = ?
任何指示都会有帮助

使用

console.log(Date.next().friday())

您可以在不使用任何库的情况下使用JS实现这一点

首先,找出当前日期代表的“天”<代码>新日期()。getDay()将返回0(星期日)-6(星期六)之间的值。现在你知道一周中的哪一天了,你可以简单地做一点数学来计算下一个最近的星期五是什么时候

const now = new Date();
// The next friday is this many days away. Actually this is a current/next
// thursday and we are adding a day so we can simplify the expression.
const offset =  ((11 - date.getDay()) % 7) + 1;

now.setDate(now.getDate() + offset); // add days to friday to our time.
因此,您可以将其封装到一个函数中,并将其粘贴到某个帮助文件中。您甚至可以参数化日期,以便可以找到任意日期

const today = new Date("09/13/2020");

const nextDay = (date, day) => {
  const result = new Date(date.getTime());
  const offset = (((day + 6) - date.getDay()) % 7) + 1;
  
  result.setDate(date.getDate() + offset);

  return result;
};

const days = {
  sunday: 0,
  monday: 1,
  tuesday: 2,
  wednesday: 3,
  thursday: 4,
  friday: 5,
  saturday: 6
};

const nextFriday = (date) => nextDay(date, days.friday);

console.log(nextFriday(today)); // hopefully 9/18/2020
格式化将只是从结果日期查找每个组件并将它们连接在一起

const today = new Date("09/13/2020");

const formatDate = (date) => {
  const month = `${date.getMonth() + 1}`.padStart(2, "00");
  const day = `${date.getDate()}`.padStart(2, "00");
  const year = date.getFullYear();
  
  return `${month}.${day}.${year}`;
}

console.log(formatDate(today));

你包括date.js库了吗?这是一个JSFIDLE,这个
(12-date.getDay())%7
可以简化为
((11-date.getDay())%7)+1
绝对可以!完全错过了,接得好。编辑了我的答案。