IT story

JavaScript에서 날짜 / 시간을 빼는 방법?

hot-time 2020. 6. 10. 08:06
반응형

JavaScript에서 날짜 / 시간을 빼는 방법? [복제]


이 질문에는 이미 답변이 있습니다.

날짜 / 시간이 포함 된 격자에 필드가 있으며 해당 날짜와 시간의 차이를 알아야합니다. 가장 좋은 방법은 무엇입니까?

날짜는 다음과 같이 저장됩니다 "2011-02-07 15:13:06".


이렇게하면 두 날짜의 차이를 밀리 초 단위로 제공합니다

var diff = Math.abs(date1 - date2);

귀하의 예에서, 그것은

var diff = Math.abs(new Date() - compareDate);

그것이 compareDate유효한 Date객체 인지 확인해야 합니다.

이 같은 것이 아마 당신을 위해 일할 것입니다

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

즉, 회전 "2011-02-07 15:13:06"new Date('2011/02/07 15:13:06')는 A 형식 인 Date생성자는 이해할 수 있습니다.


두 개의 날짜 개체를 빼기 만하면됩니다.

var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01")  // some date
var diff = Math.abs(d1-d2);  // difference in milliseconds

동일한 브라우저 클라이언트에서 날짜를 빼지 않고 일광 절약 시간제 변경과 같은 최첨단 사례를 신경 쓰지 않는 한 강력한 현지화 된 API를 제공 하는 moment.js사용 하는 것이 좋습니다 . 예를 들어, 이것은 내 utils.js에있는 것입니다.

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();
},

1970 년 1 월 1 일 이후 getTime()로 method를 사용 하여 Date밀리 초 수로 변환 할 수 있습니다. 그런 다음 날짜를 사용하여 산술 연산을 쉽게 수행 할 수 있습니다. 물론 숫자를 Datewith로 다시 변환 할 수 있습니다 setTime(). 여기 예를 참조 하십시오 .


현지 시간대 및 일광 절약 시간제를 사용하여 벽시계 시간의 차이를 얻으려면


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

테스트


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});

분 또는 초의 차이는 같은 방식입니다.

참고 URL : https://stackoverflow.com/questions/4944750/how-to-subtract-date-time-in-javascript

반응형