program story

JavaScript로 날짜를 더하거나 빼는 방법은 무엇입니까?

inputbox 2020. 11. 10. 08:04
반응형

JavaScript로 날짜를 더하거나 빼는 방법은 무엇입니까?


사용자가 날짜별로 항목을 검색 할 수 있도록 JavaScript를 사용하여 날짜를 쉽게 추가하고 뺄 수 있도록하고 싶습니다.

날짜 형식은 "mm / dd / yyyy"입니다. 나는 그들이 "다음"버튼을 클릭 할 수 있기를 원하고, 날짜가 "06/01/2012"이면 다음을 클릭하면 "06/02/2012"가되어야합니다. '이전'버튼을 클릭하면 '2012 년 5 월 31 일'이됩니다.

윤년, 월의 일수 등을 추적해야합니다.

어떤 아이디어?

AJAX를 사용하여 서버에서 날짜를 가져 오는 PS는 옵션이 아니며 클라이언트가 원하는 사용자의 경험이 아니라 약간 느립니다.


암호:

var date = new Date('2011', '01', '02');
alert('the original date is ' + date);
var newdate = new Date(date);

newdate.setDate(newdate.getDate() - 7); // minus the date

var nd = new Date(newdate);
alert('the new date is ' + nd);

Datepicker 사용 :

$("#in").datepicker({
    minDate: 0,
    onSelect: function(dateText, inst) {
       var actualDate = new Date(dateText);
       var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
        $('#out').datepicker('option', 'minDate', newDate );
    }
});

$("#out").datepicker();​

JSFiddle 데모

유용 할 수있는 추가 항목 :

getDate()   Returns the day of the month (from 1-31)
getDay()    Returns the day of the week (from 0-6)
getFullYear()   Returns the year (four digits)
getHours()  Returns the hour (from 0-23)
getMilliseconds()   Returns the milliseconds (from 0-999)
getMinutes()    Returns the minutes (from 0-59)
getMonth()  Returns the month (from 0-11)
getSeconds()    Returns the seconds (from 0-59)

좋은 링크 : MDN 날짜


당신은 사용해야 getTime()하고 setTime()자바 스크립트 Date 객체에 추가하거나 시간을 빼줄. 사용 setDate()getDate()등등 개월 1, 30, 31의 한계에 도달 할 때 오류가 발생할 것입니다 ..

setTime을 사용하면 밀리 초 단위로 오프셋을 설정하고 Date 객체가 나머지를 알아낼 수 있습니다.

var now=new Date();
var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;
now.setTime( yesterdayMs );

startdate.setDate(startdate.getDate() - daysToSubtract);


startdate.setDate(startdate.getDate() + daysToAdd);

여기에서 JavaScript Date개체가 도움이 될 수 있습니다.

첫 번째 단계는 이러한 문자열을 Date인스턴스 로 변환하는 것 입니다. 쉽게 완료됩니다.

var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10),        // Year
                  parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
                  parseInt(str.substring(3, 5), 10));    // Day

그런 다음 모든 종류의 유용한 계산을 수행 할 수 있습니다. JavaScript 날짜는 윤년 등을 이해합니다. 그들은 정확히 86,400 초 길이 의 이상화 된 "하루"개념을 사용합니다 . 기본 값은 The Epoch (1970 년 1 월 1 일 자정) 이후의 밀리 초 수입니다. The Epoch 이전 날짜의 경우 음수 일 수 있습니다.

MDN 페이지Date 에 대한 자세한 내용은 .

구문 분석, 날짜 계산, 형식 지정에 도움이되는 MomentJS 와 같은 라이브러리 사용을 고려할 수도 있습니다 .


이것이 도움이 될 수 있습니다.

    <script type="text/javascript" language="javascript">
        function AddDays(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() + parseInt(toAdd));

            document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
        }

function SubtractDays(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));

            document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
        }
    </script>
    ---------------------- UI ---------------
        <div id="result">
        </div>
        <input type="text" value="0" onkeyup="AddDays(this.value);" />
        <input type="text" value="0" onkeyup="SubtractDays(this.value);" />

//In order to get yesterday's date in mm/dd/yyyy.


function gimmeYesterday(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));
var yesterDAY = (d.getMonth() +1) + "/" + d.getDate() + "/" + d.getFullYear();
$("#endDate").html(yesterDAY);
        }
$(document).ready(function() {
gimmeYesterday(1);
});

여기에서 시도 할 수 있습니다 : http://jsfiddle.net/ZQAHE/


자바 스크립트에서 날짜로 작업하는 것은 항상 번거 롭습니다. 나는 항상 도서관을 사용합니다. Moment.js와 XDate는 모두 훌륭합니다.

http://momentjs.com/

http://arshaw.com/xdate/

깡깡이:

http://jsfiddle.net/39fWa/

var $output = $('#output'),
    tomorrow = moment().add('days', 1);

$('<pre />').appendTo($output).text(tomorrow);

tomorrow = new XDate().addDays(-1);

$('<pre />').appendTo($output).text(tomorrow);


내가 좋아하는 방식은 날짜 개체가있는 경우 다른 날짜 개체를 빼서 차이를 얻을 수 있다는 것입니다. 날짜 개체는 특정 날짜의 밀리 초를 기반으로합니다.

var date1 = new Date(2015, 02, 18); // "18/03/2015", month is 0-index
var date2 = new Date(2015, 02, 20); // "20/03/2015"

var msDiff = date2 - date1; // 172800000, this is time in milliseconds
var daysDiff = msDiff / 1000 / 60 / 60 / 24; // 2 days

그래서 이것이 날짜를 빼는 방법입니다. 이제 추가하려면? date1 + date2는 오류를 제공합니다.하지만 ms 단위로 시간을 얻으려면 다음을 사용할 수 있습니다.

var dateMs = date1 - 0;
// say I want to add 5 days I can use
var days = 5;
var msToAdd = days * 24 * 60 * 60 * 1000; 
var newDate = new Date(dateMs + msToAdd);

By subtracting 0 you turn the date object into the milliseconds format.


You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.

take a look at this object reference to learn more:

Date

Hope that helps!


All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9


var date = new Date('your date string here'); // e.g. '2017-11-21'

var newdate = new Date(date.getTime() + 24*60*60*1000 * days) // days is the number of days you want to shift the date by

This is the only solution that works reliably when adding/subtracting across months and years. Realized this after spending way too much time mucking around with the getDate and setDate methods, trying to adjust for month/year shifts.

decasteljau (in this thread) has already answered this but just want to emphasize the utility of this method because 90% of the answers out there recommend the getDate and setDate approach.


Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.

HTML:

<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />

JavaScript:

    var counter = 0;

$("#SubtractDay").click(function() {
    counter--;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
    counter++;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});

jsfiddle


The best date utility I've used is date-fns for a few reasons:

  • Uses the native JavaScript Date format.
  • Immutable; built using pure functions and always returns a new date instance instead of changing the passed one.
  • Modular; import just the functions you need.

Package manager:

"date-fns": "^1.30.1"

Code:

import { addDays, subDays } from 'date-fns'

let today = new Date()
let yesterday = subDays(today, 1)
let tomorrow = addDays(today, 1)

Simple and awesome.

참고URL : https://stackoverflow.com/questions/10931288/how-to-add-subtract-dates-with-javascript

반응형