简体   繁体   中英

Compare one date with today using DD-MM-YYYY format

I want to compare a date (mydate) with today. I tried

new Date(mydate) < new Date();

which works in all cases apart from the case my date equals today . In that case the above returns true since it compares the time included. However, I want to compare only the date , not the time.

I tried moment.js as well:

moment(mydate).format('DD-MM-YYYY')<moment().format('DD-MM-YYYY')

however, not even this one did work. What do I have to write?

You can use moment function isSame and provide the second argument as the granularity level you want for your comparison. The granularity levels can be strings like, 'year', 'month', 'day'

moment('2010-01-01').isSame('2010-02-01', 'day'); 

You can also look into similar functions documented over there which might help you better with your requirement.

  1. Is Before
  2. Is Same
  3. Is After
  4. Is Same or Before
  5. Is Same or After
  6. Is Between

All of these supports different granularity levels.

As a sidenote, to create a date in your supplied format do:

moment("25-12-1995", "DD-MM-YYYY");

You can simply do following using moment js

 $(document).ready(function() { $('.compare').click(function(e) { var date = $('#date').val(); var now = moment().format('YYYY-MM-DD'); var then = moment(date).format('YYYY-MM-DD'); if (now > then) { $('.result').text('Date is past'); } else if(now == then) { $('.result').text('Date is today'); } else { $('.result').text('Date is future'); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> <input type="text" name="date" id="date" value="2014-12-18" placeholder="yyyy-mm-dd"> <button class="compare">Compare date to current date</button> <br> <div class="result"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM