我一直试图找到一个真正快速的方法来解析yyyy-mm-dd [hh:mm:ss]到一个Date对象。以下是我尝试过的3种方法,以及每种方法分析50,000个日期时间字符串所需的时间。
castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms@H_301_5@码:
private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year,month,day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year,day,hour,minute,second); }@H_301_5@–
private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00") != -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); }@H_301_5@–
private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); }@H_301_5@不,默认情况下,Date.parse不会处理破折号。而且我需要为“0000-00-00”之类的日期时间字符串返回null。
解决方法
我一直在使用以下snipplet来解析UTC日期字符串:
private function parseUTCDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]),int(matches[2]) - 1,int(matches[3])); d.setUTCHours(int(matches[4]),int(matches[5]),int(matches[6]),0); return d; }@H_301_5@只需删除时间部分,它应该适合您的需要:
private function parseDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]),int(matches[3])); return d; }@H_301_5@不知道速度,我没有在我的应用程序中担心。在我的机器上显着少于一秒的50K次迭代。