views:

48

answers:

3

Hi,

I have a 2 different date formats. 1) dd/mm/yyyy 2) dd-mm-yyyy

I want to compare these 2 date formats in Javascript or Actionscript.

Is it possible.

Thanks, Ravi

+4  A: 

In Javascript:

x = new Date("12/12/1999")

Sun Dec 12 1999 00:00:00 GMT-0500 (Eastern Standard Time)

y = new Date("12-13-1999")

Mon Dec 13 1999 00:00:00 GMT-0500 (Eastern Standard Time)

x == y

false

x < y

true

Hope this helps!

Pete
@Pete: Thanks for your respose.Those 2 date formats are different. Can i compare it using '==' operator to compare the different dates.
Ravi K Chowdary
Sure, when you create the Date objects above, javascript normalizes the dates into its own internal formats. You then compare the date objects, instead of the strings.
Pete
A: 

The easy way in AS3 with your date in String format and if you are not interesting in the Date object itself :

        var date1Str:String="10/01/2010";
        var date2Str:String="10-01-2010";
        var equal:Boolean=date2Str.split("-").join("/")==date1Str;
        trace(equal);

If you are interesting into the date object so in AS3:

        var date1Str:String = "10/01/2010";
        var date2Str:String = "10-01-2010";

        var date1Arr:Array = date1Str.split("/");
        var date2Arr:Array = date2Str.split("-");

        var date1:Date = new Date(date1Arr[2], date1Arr[1] - 1, date1Arr[0]);
        var date2:Date = new Date(date2Arr[2], date2Arr[1] - 1, date2Arr[0]);

        var equal:Boolean = date1.getTime() == date2.getTime();
        trace(equal);
Patrick
@Patrick: Not comparing Date strings. Need to compare Date objects.
Ravi K Chowdary
@kalyaniRavi, Ok add date object also ;)
Patrick
A: 

You could convert the date strings to Date instances and compare them, I guess.

function parseDate(ds) {
  var rv = null;
  ds.replace(/(\d\d?)[-/](\d\d?)[-/](\d\d\d\d)/, function(_, dd, mm, yyyy) {
    rv = new Date(parseInt(yyyy, 10), parseInt(mm, 10) - 1, parseInt(dd, 10));
  });
  return rv;
}

// ...

if (parseDate(d1).getTime() === parseDate(d2).getTime()) {
  // ...
}

If you wanted to get fancy you could add code to cope with 2-digit years.

[edit] wow @Pete here I am a grown man and somehow I managed to avoidletting the native Date object parse date strings for me all this time :-)

Pointy