0

I have a function which convert date to my formatdate and compare it to CurrentDate. It worked well when I test it with date is a date in Octorber compare to today (16/10/2013) But if date is a date in November, the value return is true which means date < currentdate. I dont know why, anyone can explain it to me ? Thanks so much.

function IsPast(date) {
        var fullDate = new Date();
        var twoDigitMonth = fullDate.getMonth() + 1 + "";
        if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
        var twoDigitDate = fullDate.getDate() + "";
        if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
        var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
        var startDate = $.fullCalendar.formatDate(date, 'dd/MM/yyyy');

        if (startDate <= currentDate) {return true;}
        return false;
    }
Đức Bùi
  • 517
  • 1
  • 6
  • 22

2 Answers2

2

Edit: When I first read your question, I saw that you were using day first dates and jumped to my conclusion without really taking in your code. I've taken a closer look, and it appears my initial conclusion is just a red herring. The real problem is that you are taking two dates, converting them both to strings, and then trying to compare them. That's just silly - it will only tell you which string comes first alphabetically. Even sillier, is that for one of the dates you manually construct the string, but for the other one, you use a date formatting function. Why wouldn't you just use the date formatting function for both dates?

RobG's answer is correct and should be accepted.


When I see the date "01/11/2013", I read it as January 11, 2013, whereas you read it as 1 November, 2013. See the predicament the JavaScript engine is in when it tries to parse that date?*

When parsing JavaScript dates, I like to use year first dates, as these are unambiguous as far as I know. Everybody interprets "2013/11/01" as 2013 November 1. Including every JavaScript Date implementation I've seen.

Change your date format to be unambiguous.

*Frankly, I'm surprised you are seeing that behavior. I would expect that your system would be configured to expect day first dates and that the JavaScript engine would use those settings to properly parse the date. But, I'm not that surprised.

Community
  • 1
  • 1
gilly3
  • 87,962
  • 25
  • 144
  • 176
2

If you are being passed a Date object (and that seems to be what you get), then you can simply do:

function isPast(date) {
  return new Date() > date;
}

If date isn't a date object, convert it to one first.

Note that identifiers starting with a capital letter are, by convention, reserved for constructors.

RobG
  • 142,382
  • 31
  • 172
  • 209