programing

JavaScript - 현재 날짜에서 주의 첫 번째 요일을 가져옵니다.

yoursource 2022. 9. 23. 22:45
반응형

JavaScript - 현재 날짜에서 주의 첫 번째 요일을 가져옵니다.

일주일의 첫날을 잡을 수 있는 가장 빠른 방법이 필요합니다.예를 들어, 오늘은 11월 11일 목요일이고, 저는 이번 주 첫째 날인 11월 8일 월요일을 원합니다.MongoDB 맵 기능을 가장 빨리 할 수 있는 방법이 필요한데, 아이디어 있나요?

사용방법getDay날짜 객체의 메서드는 요일 수(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

또는 함수로서:

# modifies _date_
function setToMonday( date ) {
    var day = date.getDay() || 7;  
    if( day !== 1 ) 
        date.setHours(-24 * (day - 1)); 
    return date;
}

setToMonday(new Date());

CMS의 답변은 맞지만 월요일을 주의 첫 번째 요일로 가정합니다.
Chandler Zwolle의 답은 맞지만 Date 프로토타입을 만지작거리고 있다.
모든 요일이 24시간인 것은 아니기 때문에 시간/분/초/밀리초를 추가/감산하는 다른 답변은 잘못되었습니다.

다음 함수는 올바르고 날짜를 첫 번째 파라미터로, 원하는 요일을 두 번째 파라미터로 사용합니다(일요일은 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)

Date.js 확인

Date.today().previous().monday()

첫 번째/마지막 요일

다가오는 주의 첫날을 얻으려면 다음과 같은 방법을 사용할 수 있습니다.

function getUpcomingSunday() {
  const date = new Date();
  const today = date.getDate();
  const currentDay = date.getDay();
  const newDate = date.setDate(today - currentDay + 7);
  return new Date(newDate);
}

console.log(getUpcomingSunday());

또는 최신 첫날을 얻으려면:

function getLastSunday() {
  const date = new Date();
  const today = date.getDate();
  const currentDay = date.getDay();
  const newDate = date.setDate(today - (currentDay || 7));
  return new Date(newDate);
}

console.log(getLastSunday());

* 시간대에 따라서는, 요일의 시작은 일요일에 개시할 필요는 없습니다.금요일, 토요일, 월요일, 또는 머신이 설정되어 있는 그 외의 날에 개시할 수 있습니다.그 방법들이 그것을 설명해 줄 것이다.

* 를 사용하여 포맷할 수도 있습니다.toISOString다음과 같은 방법:getLastSunday().toISOString()

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;
}

이 함수는 현재 밀리초를 사용하여 현재 주를 뺀 다음 현재 날짜가 월요일(일요일부터 자바스크립트 카운트)이면 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));
}

이 방법에서는 실제로 제가 사용하는 다른 확장 방법을 사용하고 있습니다.

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);

안부 전해요,

setDate()에는 위의 코멘트에 기재되어 있는 월 경계에 관한 문제가 있습니다.깔끔한 회피책은 날짜 객체의 (놀랍게도 직관에 반하는) 메서드가 아닌 에폭 타임스탬프를 사용하여 날짜 차이를 찾는 것입니다.예.

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);
}

저의 솔루션은 다음과 같습니다.

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;
}

이제 반환된 어레이 인덱스로 날짜를 선택할 수 있습니다.

수 이며, 으로만 사용할 수 있습니다.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

이것을 좀 더 일반화한 것...그러면 지정한 요일에 따라 해당 주의 요일이 표시됩니다.

//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);

월요일 오전 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)

일주일 중 첫 요일을 얻기 위한 간단한 솔루션.

이 솔루션을 사용하면 임의의 주 시작(예: 일요일 = 0, 월요일 = 1, 화요일 = 2 등)을 설정할 수 있습니다.

function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
    const result = new Date(date);
    while (result.getDay() !== startOfWeek) {
        result.setDate(result.getDate() - 1);
    }
    return result;
}
  • 솔루션이 몇 개월로 올바르게 마무리됨(사용으로 인해)
  • ★★★의 startOfWeek, 와 같은 상수값을 사용할 수 있습니다.

현지 시간과 UTC를 구별하는 것이 중요합니다.UTC에서 요일의 시작을 찾고 싶었기 때문에 다음 기능을 사용했습니다.

function start_of_week_utc(date, start_day = 1) {

// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.

    date = new Date(date);
    const day_of_month = date.getUTCDate();
    const day_of_week = date.getUTCDay();
    const difference_in_days = (
        day_of_week >= start_day
        ? day_of_week - start_day
        : day_of_week - start_day + 7
    );
    date.setUTCDate(day_of_month - difference_in_days);
    date.setUTCHours(0);
    date.setUTCMinutes(0);
    date.setUTCSeconds(0);
    date.setUTCMilliseconds(0);
    return date;
}

특정 시간대 내에서 한 주의 시작을 찾으려면 먼저 시간대 오프셋을 입력 날짜에 추가한 후 출력 날짜에서 뺍니다.

const local_start_of_week = new Date(
    start_of_week_utc(
        date.getTime() + timezone_offset_ms
    ).getTime() - timezone_offset_ms
);

나는 이것을 사용한다.

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;
}

잘 되고 있어요.

UTC-XX:XX 시간대에 코드를 실행하는 사용자에게는 승인된 답변이 적용되지 않습니다.

다음은 날짜만 시간대에 관계없이 작동하는 코드입니다.이것도 시간을 주면 안 돼요.날짜 또는 구문 분석 날짜만 제공하고 입력으로 제공하십시오.코드 시작 부분에서 다른 테스트 케이스를 언급했습니다.

function getDateForTheMonday(dateString) {
  var orignalDate = new Date(dateString)
  var modifiedDate = new Date(dateString)
  var day = modifiedDate.getDay()
  diff = modifiedDate.getDate() - day + (day == 0 ? -6:1);// adjust when day is sunday
  modifiedDate.setDate(diff)

  var diffInDate = orignalDate.getDate() - modifiedDate.getDate()
  if(diffInDate == 6) {
    diff = diff + 7
    modifiedDate.setDate(diff)
  }
  console.log("Given Date : " + orignalDate.toUTCString())
  console.log("Modified date for Monday : " + modifiedDate)
}

getDateForTheMonday("2022-08-01") // Jul month with 31 Days
getDateForTheMonday("2022-07-01") // June month with 30 days
getDateForTheMonday("2022-03-01") // Non leap year February
getDateForTheMonday("2020-03-01") // Leap year February
getDateForTheMonday("2022-01-01") // First day of the year
getDateForTheMonday("2021-12-31") // Last day of the year

체크아웃: 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에서도 동작합니다.

언급URL : https://stackoverflow.com/questions/4156434/javascript-get-the-first-day-of-the-week-from-current-date

반응형