JavaScript-현재 날짜에서 첫 번째 요일 가져 오기
주중 첫날을 얻는 가장 빠른 방법이 필요합니다. 예를 들어 오늘은 11 월 11 일과 목요일입니다. 11 월 8 일인 월요일과 월요일 인 이번 주 첫날을 원합니다. MongoDB 맵 기능, 아이디어가 가장 빠른 방법이 필요합니까?
getDay
Date 객체 의 메서드를 사용하여 요일 (0 = 일요일, 1 = 월요일 등)을 알 수 있습니다.
그런 다음 해당 일 수에 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
성능과 어떻게 비교되는지 확실하지 않지만 작동합니다.
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());
Date.js를 확인하십시오
Date.today().previous().monday()
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));
이것은 잘 작동합니다.
나는 이것을 사용하고있다
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;
}
CMS의 답변은 정확하지만 월요일은 주중 첫날이라고 가정합니다.
챈들러 즈 볼레의 대답은 정확하지만 날짜 프로토 타입과는 다릅니다.
시간 / 분 / 초 / 밀리 초로 재생되는 다른 답변이 잘못되었습니다.
아래 함수는 정확하며 날짜를 첫 번째 매개 변수로, 원하는 요일을 두 번째 매개 변수로 사용합니다 (일요일은 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)
이 함수는 현재 밀리 초 시간을 사용하여 현재 주를 빼고 현재 날짜가 월요일 (일요일부터 자바 스크립트 수) 인 경우 1 주를 더 뺍니다.
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;
}
일주일이 한 달에서 다른 달 (그리고 몇 년)에 걸쳐있을 때 테스트했으며 제대로 작동하는 것 같습니다.
안녕하세요,
간단한 확장 방법을 선호합니다.
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:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
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);
}
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.
Check out: moment.js
Example:
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)
Bonus: works with node.js too
'IT' 카테고리의 다른 글
파이썬에서 mod b를 계산하는 방법은 무엇입니까? (0) | 2020.06.25 |
---|---|
네트워크 케이블 / 커넥터의 물리적 연결 상태를 감지하는 방법은 무엇입니까? (0) | 2020.06.25 |
해시 할 Rails 객체 (0) | 2020.06.25 |
onSaveInstanceState () 및 onRestoreInstanceState () (0) | 2020.06.25 |
정규식을 사용하여 bash에서 검색 및 바꾸기 (0) | 2020.06.25 |