JavaScript - 从当前日期获取一周的第一天 [英] JavaScript - get the first day of the week from current date

查看:32
本文介绍了JavaScript - 从当前日期获取一周的第一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以最快的方式获得一周的第一天.例如:今天是11月11日,星期四;我想要本周的第一天,也就是 11 月 8 日,还有一个星期一.我需要 MongoDB map 函数的最快方法,有什么想法吗?

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?

推荐答案

使用 Date 对象的 getDay 方法,可以知道星期几(0=星期日,1=星期一等).

Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).

然后您可以减去该天数加一,例如:

You can then subtract that number of days plus one, for example:

function getMonday(d) {
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
  return new Date(d.setDate(diff));
}

getMonday(new Date()); // Mon Nov 08 2010

这篇关于JavaScript - 从当前日期获取一周的第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆