JavaScript - 从当前日期获取一周的第一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4156434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - get the first day of the week from current date
提问by INs
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?
我需要最快的方法来获得一周的第一天。例如:今天是 11 月 11 日,星期四;我想要本周的第一天,也就是 11 月 8 日,还有一个星期一。我需要 MongoDB map 函数的最快方法,有什么想法吗?
回答by CMS
Using the getDay
method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
使用getDay
Date 对象的方法,您可以知道一周中的天数(0=星期日,1=星期一等)。
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
回答by user113716
Not sure how it compares for performance, but this works.
不确定它的性能比较如何,但这是有效的。
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
Or as a function:
或者作为一个函数:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
回答by Louis Ameline
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that play with hour/minutes/seconds/milliseconds are wrong.
CMS 的答案是正确的,但假设星期一是一周的第一天。
Chandler Zwolle 的回答是正确的,但对 Date 原型进行了摆弄。
使用小时/分钟/秒/毫秒的其他答案是错误的。
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
下面的函数是正确的,将日期作为第一个参数,将所需的一周中的第一天作为第二个参数(星期日为 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)
回答by Parth Shah
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));
This will work well.
这将运作良好。
回答by 1nstinct
I'm using this
我正在使用这个
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;
}
回答by einord
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
此函数使用当前毫秒时间减去当前周,如果当前日期是星期一(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;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
当一周从一个月跨到另一个(以及几年)时,我已经对其进行了测试,并且它似乎可以正常工作。
回答by Chandler Zwolle
Good evening,
晚上好,
I prefer to just have a simple extension method:
我更喜欢有一个简单的扩展方法:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
您会注意到这实际上使用了我使用的另一种扩展方法:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
现在,如果您的星期从星期日开始,请为 pStartOfWeek 参数传入“0”,如下所示:
var mThisSunday = new Date().startOfWeek(0);
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
同样,如果您的星期从星期一开始,请为 pStartOfWeek 参数传入“1”:
var mThisMonday = new Date().startOfWeek(1);
var mThisMonday = new Date().startOfWeek(1);
Regards,
问候,
回答by Lior Elrom
First Day of The Week
一周的第一天
To get the date of the first day of the week from today, you can use something like so:
要从今天开始获取一周的第一天的日期,您可以使用以下方法:
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());
Or to get the last day of the week from today:
或者从今天开始获取一周的最后一天:
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());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* 根据您的时区,一周的开始不必从星期日开始,它可以从星期五、星期六、星期一或您的机器设置的任何其他日期开始。这些方法将说明这一点。
* You can also format it using toISOString
method like so: getLastSunday().toISOString()
* 您也可以使用如下toISOString
方法对其进行格式化:getLastSunday().toISOString()
回答by Krystian Wieczorek
Here is my solution:
这是我的解决方案:
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;
}
Now you can pick date by returned array index.
现在您可以通过返回的数组索引来选择日期。