현재 날짜를 이전 10 일 및 이후 10 일로 변환

Aug 19 2020

현재 날짜를이 형식으로 변환하는 코드가 2020-08-20있습니다. 하지만 변경 어떻게이 일 십일에게 나에게주는 from오늘 10 일 before오늘.

예를 들어 오늘은 2020-08-20오늘부터 10 일을하려고합니다.2020-08-30

이것은 내 코드입니다

const dateConverter = (dateIn) => {
        var year = dateIn.getFullYear();
        var month = dateIn.getMonth() + 1; // getMonth() is zero-based
        var day = dateIn.getDate();
        return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
      }
      
      var today = new Date();
      console.log(dateConverter(today));

답변

2 Sascha Aug 19 2020 at 21:55

약간 까다 롭습니다. 여름 / 겨울 변경 문제를 방지하기 위해 먼저 날짜에서 12 시간으로 시간을 설정합니다. 그런 다음 getDate추가 일수와 setDate새 값 에 10을 추가하십시오 . 이제 밀리 초 단위의 값이 있으므로이 날짜에서 새 날짜를 생성하여 dateobject를 가져옵니다. 두 번째 날짜의 경우 원래 날짜가 이전 작업에 의해 변경되었으므로 20 일을 빼고 다른 모든 작업을 동일하게 수행합니다.

와 날짜에 대한 출력 형식 getFullYear, getMonth그리고 getDate. 월은 JS에서 0에서 11까지 처리되기 때문에 1 개월을 추가합니다. 월과 일은 1 자리가 될 수 있지만 2 자리를 원하므로 문자열 앞에 추가 "0"하고 slice.
두 날짜에 대해 형식을 지정하고 배열로 반환합니다.

const dateConverter = (dateIn) => {
    dateIn.setHours(12);
    let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
    let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
    
    let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
    let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
    return [strFor10Days, strIn10Days];
}
      
let today = new Date();
console.log(dateConverter(today));

2 Hasan_Naser Aug 19 2020 at 21:51

이 코드는 당신을 도울 것입니다

오늘부터 7 일 전까지 JavaScript 계산 날짜 참조

10 일 후에는-를 +로 변환하십시오.

    const dateConverter = (dateIn) => { 
         var dates ={};

         var days = 10; // Days you want to subtract



         for(let i=0;i<days;i++){


           var date = dateIn;

           var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));

           var day = last.getDate();

           var month= last.getMonth()+1;

           var year= last.getFullYear();

           dates[i] =  year + "-" + month.toString().padStart(2, "0") + "-" +                             day.toString().padStart(2, "0");


         }


          return dates

      }
      
      var today = new Date();
      console.log(dateConverter(today));
       

1 Chilarai Aug 19 2020 at 21:41

이 시도

const dateConverter = (dateIn) => {
    var year = dateIn.getFullYear();
    var month = dateIn.getMonth() + 1; // getMonth() is zero-based
    var day = dateIn.getDate();
    return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}

var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd); 
console.log(dateConverter(today));


var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract); 
console.log(dateConverter(today));
1 Ashok Aug 19 2020 at 21:47

순간 라이브러리를 사용하는 것이 좋지만 여전히 일반 자바 스크립트를 원합니다.

const convert = (date) => {
 const pastDate = new Date(date)
 pastDate.setDate(pastDate.getDate() - 10); 
 const futureDate = new Date(date)
 futureDate.setDate(futureDate.getDate() + 10); 
 return { pastDate, futureDate } 
}

모든 날짜로 변환 함수를 호출하십시오.

ThaekeHekkenberg Aug 19 2020 at 21:40

나는 전에도 그 문제를 해결했습니다. 하지만이 스택 오버플로에서 정말 좋은 답을 찾을 수 있습니다. JavaScript 날짜에 요일 추가

Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}

var date = new Date();

alert(date.addDays(5));

이 게시물에서 가져온 코드입니다.

일을 빼려면 "+ 일"을 "-일"로 바꾸십시오.

이것이 문제가 해결되기를 바랍니다!

messerbill Aug 19 2020 at 21:42

모든 날짜를로 변환 timestamp한 다음 간단히 계산할 수 있습니다.

const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))