开发者

Comparing two different date formats

开发者 https://www.devze.com 2022-12-21 14:09 出处:网络
I have a 2 different date formats. 1) dd/mm/yyyy 2) dd-mm-yyyy I want to compare these 2 date formats in Java开发者_StackOverflow中文版script or Actionscript.

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

I want to compare these 2 date formats in Java开发者_StackOverflow中文版script or Actionscript.

Is it possible?


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!


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);


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 :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号