Programing

Moment JS-날짜가 오늘인지 또는 미래인지 확인

lottogame 2020. 5. 11. 07:59
반응형

Moment JS-날짜가 오늘인지 또는 미래인지 확인


momentjs주어진 날짜가 오늘인지 또는 미래인지 확인 하는 데 사용하려고합니다 .

이것이 내가 지금까지 가진 것입니다.

<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript">

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment().diff(SpecialTo) > 0) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

</script>

코드는 내 날짜 (2014 년 1 월 31 일)를 과거 날짜로 평가하고 있습니다.

내가 뭘 잘못하고 있는지 알아?


http://momentjs.com/docs/#/displaying/difference/ 문서를 읽은 후에 diff는 빼기 연산자와 같은 기능 을 고려해야합니다 .

                   // today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0

따라서 상태 반대로 해야합니다.

모든 것이 올바른지 확인하려면 함수에 추가 매개 변수를 추가 할 수 있습니다.

moment().diff(SpecialTo, 'days') // -8 (days)

isSame기능을 사용할 수 있습니다 :

var iscurrentDate = startTime.isSame(new Date(), "day");
if(iscurrentDate) {

}

// Returns true if it is today or false if it's not
moment(SpecialToDate).isSame(moment(), 'day');

isAfter()momentjs 쿼리 기능을 사용할 수 있습니다 .

순간이 다른 순간 이후인지 확인하십시오.

moment('2010-10-20').isAfter('2010-10-19'); // true

단위를 밀리 초가 아닌 다른 단위로 제한하려면 두 번째 매개 변수로 단위를 전달하십시오.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false

moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

http://momentjs.com/docs/#/query/is-after/


아직 언급 한 사람이 없으므로 Moment 날짜 객체가 과거인지 확인하는 가장 간단한 방법은 다음과 같습니다.

momentObj.isBefore()

또는 미래에 :

momentObj.isAfter()

args를 비워 두십시오. 기본값은 지금입니다.

이이기도 isSameOrAfter하고 isSameOrBefore.

NB 이것은 시간의 요소입니다. 하루 만 걱정한다면 Dipendu의 답변을 참조하십시오 .


날짜가 오늘과 같은지 또는 다음과 같은지 여부를 확인하는 순간 이전의 방법 :

!moment(yourDate).isBefore(moment(), "day");

오늘인지 확인하려면 :

시간 정보를 포함하는 두 날짜를 비교 isSame하면 분명히 실패합니다. diff두 날짜가 새로운 날에 걸쳐있는 경우 실패합니다.

var date1 = moment("01.01.2016 23:59:00", "DD.MM.YYYY HH.mm.ss");
var date2 = moment("02.01.2016 00:01:00", "DD.MM.YYYY HH.mm.ss");
var diff = date2.diff(date1); // 2seconds

I think the best way, even if it is not quick and short, is the following:

var isSame = date1.date() == date2.date() && date1.month() == date2.month() && date1.year() == date2.year()

To check if it is in the future:

As suggested also by other users, the diff method works.

var isFuture = now.diff(anotherDate) < 0 

If you only need to know which one is bigger, you can also compare them directly:

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment() > SpecialTo) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

Hope this helps!


Just in case someone else needs this, just do this:

const isToday = moment(0, "HH").diff(date, "days") == 0;

or if you want a function:

isToday = date => moment(0,"HH").diff(date, "days") == 0;

Where date is the date you want to check for.

Explanation

moment(0, "HH") returns today's day at midnight.

date1.diff(date2, "days") returns the number of days between the date1 and date2.

Update

I have since found the isSame function, which in I believe is the correct function to use for figuring out if a date is today:

moment().isSame('2010-02-01', 'day'); // Return true if we are the 2010-02-01

if firstDate is same or after(future) secondDate return true else return false. Toda is firstDate = new Date();

  static isFirstDateSameOrAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isSameOrBefore(date2,'day');
    }
    return false;
  }

There is isSame, isBefore and isAfter for day compare moment example;

  static isFirstDateSameSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if (date1 && date2) {
      return date1.isSame(date2,'day');
    }
    return false;
  }

  static isFirstDateAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isAfter(date2,'day');
    }
    return false;
  }

  static isFirstDateBeforeSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isBefore(date2,'day');
    }
    return false;
  }

Use the simplest one to check for future date

if(moment().diff(yourDate) >=  0)
     alert ("Past or current date");
else
     alert("It is a future date");

function isTodayOrFuture(date){
  date = stripTime(date);
  return date.diff(stripTime(moment.now())) >= 0;
}

function stripTime(date){
  date = moment(date);
  date.hours(0);
  date.minutes(0);
  date.seconds(0);
  date.milliseconds(0);
  return date;
}

And then just use it line this :

isTodayOrFuture(YOUR_TEST_DATE_HERE)

Select yesterday to check past days or not with help of moment().subtract(1, "day");

Reference:- http://momentjs.com/docs/#/manipulating/subtract/

function myFunction() {
  var yesterday = moment().subtract(1, "day").format("YYYY-MM-DD");
  var SpecialToDate = document.getElementById("theDate").value;

  if (moment(SpecialToDate, "YYYY-MM-DD", true).isAfter(yesterday)) {
    alert("date is today or in future");
    console.log("date is today or in future");
  } else {
    alert("date is in the past");
    console.log("date is in the past");
  }
}
<script src="http://momentjs.com/downloads/moment.js"></script>
<input type="date" id="theDate" onchange="myFunction()">


i wanted it for something else but eventually found a trick which you can try

somedate.calendar(compareDate, { sameDay: '[Today]'})=='Today'

var d = moment();
 var today = moment();
 
 console.log("Usign today's date, is Date is Today? ",d.calendar(today, {
    sameDay: '[Today]'})=='Today');
    
 var someRondomDate = moment("2012/07/13","YYYY/MM/DD");
 
 console.log("Usign Some Random Date, is Today ?",someRondomDate.calendar(today, {
    sameDay: '[Today]'})=='Today');
    
  
 var anotherRandomDate =  moment("2012/07/13","YYYY/MM/DD");
 
 console.log("Two Random Date are same date ? ",someRondomDate.calendar(anotherRandomDate, {
    sameDay: '[Today]'})=='Today');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


If we want difference without the time you can get the date different (only date without time) like below, using moment's format.

As, I was facing issue with the difference while doing ;

moment().diff([YOUR DATE])

So, came up with following;

const dateValidate = moment(moment().format('YYYY-MM-DD')).diff(moment([YOUR SELECTED DATE HERE]).format('YYYY-MM-DD'))

IF dateValidate > 0 
   //it's past day
else
   //it's current or future

Please feel free to comment if there's anything to improve on.

Thanks,

참고URL : https://stackoverflow.com/questions/21284312/moment-js-check-if-a-date-is-today-or-in-the-future

반응형