Programing

JavaScript에서 날짜 증가

lottogame 2020. 2. 26. 07:37
반응형

JavaScript에서 날짜 증가


JavaScript에서 날짜 값을 하루 씩 증가시켜야합니다.

예를 들어 날짜 값이 2010-09-11이며 다음 날의 날짜를 JavaScript 변수에 저장해야합니다.

날짜를 하루 단위로 늘리려면 어떻게해야합니까?


세 가지 옵션 :

1. JavaScript Date객체 만 사용 (라이브러리 없음) :

# 1에 대한 이전의 대답은 잘못되었습니다 (24 시간이 추가되어 일광 절약 시간으로의 전환을 설명하지 못했습니다. Clever Human 은 동부 표준시에서 2010 년 11 월 7 일에 실패 할 것이라고 지적했습니다). 대신 Jigar의 답변 은 라이브러리 없이이 작업을 수행하는 올바른 방법입니다.

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

JavaScript 날짜 객체는 롤오버에 대해 똑똑하기 때문에 한 달의 마지막 날에도 작동합니다.

var lastDayOf2015 = new Date(2015, 11, 31);
snippet.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
snippet.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
snippet.log("Resulting date: " + nextDay.toISOString());
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

(이 답변은 현재 승인되었으므로 삭제할 수 없습니다. 승인되기 전에 OP에 Jigar를 수락하도록 제안했지만 목록의 항목 # 2 또는 # 3에 대해이 답변을 수락했을 것입니다.)

2. MomentJS 사용 :

var today = moment();
var tomorrow = moment(today).add(1, 'days');

( add새 인스턴스를 반환하지 않고 호출하는 인스턴스 수정하면 today.add(1, 'days')수정 today됩니다. 따라서 복제 작업을 시작합니다 var tomorrow = ....)

3. DateJS 사용 하지만 오랜 시간 동안 업데이트되지 않았습니다.

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

이 답변의 예제 중 어느 것도 일광 절약 시간 조정 요일과 작동하지 않는 것 같습니다. 그 날의 하루 수는 24 시간이 아닙니다 ( "스프링 포워드"또는 "폴백"여부에 따라 23 또는 25입니다).

아래의 AddDays 자바 스크립트 함수는 일광 절약 시간제를 설명합니다.

function addDays(date, amount) {
  var tzOff = date.getTimezoneOffset() * 60 * 1000,
      t = date.getTime(),
      d = new Date(),
      tzOff2;

  t += (1000 * 60 * 60 * 24) * amount;
  d.setTime(t);

  tzOff2 = d.getTimezoneOffset() * 60 * 1000;
  if (tzOff != tzOff2) {
    var diff = tzOff2 - tzOff;
    t += diff;
    d.setTime(t);
  }

  return d;
}

함수 테스트에 사용한 테스트는 다음과 같습니다.

    var d = new Date(2010,10,7);
    var d2 = AddDays(d, 1);
    document.write(d.toString() + "<br />" + d2.toString());

    d = new Date(2010,10,8);
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, 1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

가장 쉬운 방법은 밀리 초로 변환하고 1000 * 60 * 60 * 24 밀리 초를 추가하는 것입니다. 예 :

var tomorrow = new Date(today.getTime()+1000*60*60*24);

내일 순수 JS에서 한 줄에 있지만 추한 것입니다 !

new Date(new Date().setDate(new Date().getDate() + 1))

결과는 다음과 같습니다.

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

다른 사람들의 제안을 따르기 전에 먼저 문자열을 구문 분석해야합니다.

var dateString = "2010-09-11";
var myDate = new Date(dateString);

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

다시 같은 형식으로 되돌리려면 "수동으로"해야합니다.

var y = myDate.getFullYear(),
    m = myDate.getMonth() + 1, // january is month 0 in javascript
    d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");

그러나 다른 답변에서 언급 한대로 Date.js를 얻는 것이 좋습니다 . 많은 도움이 될 것 입니다.


다음 5 일 얻기 :

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}

두 가지 방법 :

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2 : 이전 방법과 유사

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)

dateObj.toJSON () 메서드를 사용하여 날짜의 문자열 값을 가져옵니다. Ref : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON 반환 된 날짜에서 날짜를 슬라이스 값을 입력 한 다음 원하는 일 수만큼 증가시킵니다.

var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);

BUG (Firefox 32.0.3 및 Chrome 38.0.2125.101)인지 확실하지 않지만 브라질 (-3 GMT)에서는 다음 코드가 실패합니다.

Date.prototype.shiftDays = function(days){    
  days = parseInt(days, 10);
  this.setDate(this.getDate() + days);
  return this;
}

$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");

결과:

Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200

날짜에 1 시간을 추가하면 완벽하게 작동하지만 문제는 해결되지 않습니다.

$date = new Date(2014, 9, 16,0,1,1);

결과:

Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200

 Date.prototype.AddDays = function (days) {
    days = parseInt(days, 10);
    return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}

var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));

결과

2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z

내일 날짜를 문자열로 표시합니다. new Date ()를 사용하여 오늘 날짜를 가져오고 Date.getDate () 및 Date.setDate ()를 사용하여 하루를 추가하고 Date 객체를 문자열로 변환합니다.

  const tomorrow = () => {
      let t = new Date();
      t.setDate(t.getDate() + 1);
      return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
        t.getDate()
      ).padStart(2, '0')}`;
    };
    tomorrow();

바닐라 js로 날짜 연도 증가 :

start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020

누군가가 날짜 (일) 이외의 다른 값을 늘리려는 경우를 대비하여


네이티브 JS를 통해 하루를 추가하려면 다음을 수행하십시오.

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

또 다른 옵션은 moment라이브러리 를 사용하는 것입니다 .

const date = moment().add(14, "days").toDate()

참고 URL : https://stackoverflow.com/questions/3674539/incrementing-a-date-in-javascript



반응형