我需要以最快的方式来获得一周的第一天。例如:今天是11月11日,星期四;我想要本周的第一天,也就是11月8日和星期一。我需要MongoDB地图功能最快的方法,任何想法?
答案 0 :(得分:255)
使用Date对象的getDay
方法,您可以知道星期几的数量(0 =星期日,1 =星期一等)。
然后您可以减去该天数加一,例如:
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
答案 1 :(得分:45)
不确定它如何与性能进行比较,但这可行。
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
或作为一项功能:
function getMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
getMonday(new Date());
答案 2 :(得分:13)
查看Date.js
Date.today().previous().monday()
答案 3 :(得分:4)
我正在使用此
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
答案 4 :(得分:4)
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
这样做会很好。
答案 5 :(得分:4)
要获取从今天开始的一周中第一天的日期,您可以使用类似这样的方法:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const dayOfTheWeek = date.getDay();
const newDate = date.setDate(today - dayOfTheWeek + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
或者从今天开始获取一周的最后一天:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const dayOfTheWeek = date.getDay();
const newDate = date.setDate(today - (dayOfTheWeek || 7));
return new Date(newDate);
}
console.log(getLastSunday());
*根据您所在的时区,一周的开始不必在星期日开始,它可以在星期五,星期六,星期一或您的计算机设置的任何其他日期开始。这些方法将解决这个问题。
*您也可以使用toISOString
方法对其进行格式化,如下所示:getLastSunday().toISOString()
答案 6 :(得分:3)
此函数使用当前毫秒时间减去当前周,然后如果当前日期是星期一,则减去一周(javascript从星期日算起)。
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
我已经测试了一周,从一个月到另一个月(以及几年),它似乎正常工作。
答案 7 :(得分:3)
CMS的答案是正确的,但假定星期一是一周的第一天。
钱德勒·兹沃勒(Chandler Zwolle)的回答是正确的,但摆弄了日期原型。
其他以小时/分钟/秒/毫秒为单位的答案是错误的。
下面的函数是正确的,并将日期作为第一个参数,并将所需的一周的第一天作为第二个参数(0代表星期日,1代表星期一,依此类推)。注意:小时,分钟和秒设置为0,以表示一天的开始。
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
答案 8 :(得分:2)
晚上好,
我更喜欢只有一个简单的扩展方法:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
您会注意到这实际上使用了我使用的另一种扩展方法:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
现在,如果您的周数从星期日开始,请为pStartOfWeek参数传递“0”,如下所示:
var mThisSunday = new Date().startOfWeek(0);
同样,如果您的周数从星期一开始,则为pStartOfWeek参数传递“1”:
var mThisMonday = new Date().startOfWeek(1);
此致
答案 9 :(得分:1)
结帐: moment.js
示例:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
奖励:也适用于node.js
答案 10 :(得分:1)
setDate()存在上述评论中注明的月份边界问题。一个干净的解决方法是使用纪元时间戳找到日期差异,而不是使用Date对象上的(令人惊讶的违反直觉的)方法。即。
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
答案 11 :(得分:1)
这是我的解决方案:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
现在您可以通过返回的数组索引选择日期。
答案 12 :(得分:0)
没有任何Date
函数的纯数学计算示例。
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
答案 13 :(得分:0)
此版本的更通用的版本...这将根据您指定的日期为您提供当前一周中的任意一天。
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
答案 14 :(得分:0)
周一早上 00 点到周一早上 00 点返回。
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
答案 15 :(得分:0)
我用这个:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
效果很好。