-1

I am trying to compare two java script dates using greater than operator but it is not working ,i am posting my code ,

select : function(date, jsEvent, allDay) {
        $('#clickedDateHolder').val(date.format());
        var check = date.format();

        var date = new Date();

        var day = date.getDate();
        var month = date.getMonth();
        var year = date.getFullYear();
        var currentDate = year +'-'+month+'-'+day; 
        // show modal dialog

        alert('check :'+check +'currentDate :'+currentDate)
        if(check < currentDate)
        {
            bootbox.alert("Past Dates")
        }else if(check > currentDate){ 
            input.push(date.format());
            $('#selectedDate').val(input);
            $('#event-modal').modal('show');

        }

date.format(); is giving me the selected date and i am formatting the current date using

    var day = date.getDate();
    var month = date.getMonth();
    var year = date.getFullYear();
    var currentDate = year +'-'+month+'-'+day; 

but when i am using the greater than operator it is not working .The two date formats which are generated are

check :2015-10-27 currentDate :2015-9-29

How to solve this?? please help

Subho
  • 921
  • 5
  • 25
  • 48
  • What is "not working"? Does it alert `"Past Dates"` unexpectedly? – Bergi Oct 29 '15 at 11:26
  • @Bergi yes always past dates alert is showing – Subho Oct 29 '15 at 11:27
  • @Bergi then how to solve this ?? – Subho Oct 29 '15 at 11:29
  • @Subho try to use http://momentjs.com/, it has method for comparison –  Oct 29 '15 at 11:30
  • 1
    @Subho: You should not compare dates as strings - just use `Date` objects. And if you still do, make sure that they have the same format, currently it's not working because `9` > `1`. – Bergi Oct 29 '15 at 11:30
  • @Bergi should i convert the String to date object ?? – Subho Oct 29 '15 at 11:31
  • @Subho: Yes, exactly. And then simply compare against `new Date` directly. – Bergi Oct 29 '15 at 11:38
  • @Bergi can you edit my code ?? please – Subho Oct 29 '15 at 11:50
  • @Bergi i am doing new Date(currentDate ) but it is not converting – Subho Oct 29 '15 at 12:10
  • When you compare 2 date objects, object being reference type, will always return false. Try `date.getTime()` or `+date` – Rajesh Oct 29 '15 at 12:58
  • @Rajesh: Not with `>` `<` `<=` `=>` operators. His problem is that he doesn't compare *date objects*. – Bergi Oct 29 '15 at 13:50
  • @Subho: You shouldn't need to use the `currentDate` string at all - `date` is already a `new Date()` object! Rather `new Date(check)`, though it seems that the `date` parameter of your function already gets a `Date` object anyway. Just don't `format()` the values you're comparing. – Bergi Oct 29 '15 at 13:52

1 Answers1

-1

You can get the time in milliseconds

 check > new Date() // currentDate = new Date(), your string breaks it.
Olavi Sau
  • 1,647
  • 13
  • 20