apache-flex - Actionscript 3 - 解析 yyyy-mm-dd hh :mm:ss to a Date object? 的最快方法

标签 apache-flex actionscript-3

我一直试图找到一种非常快速的方法来将 yyyy-mm-dd [hh:mm:ss] 解析为 Date 对象。以下是我尝试过的 3 种方法,以及每种方法解析 50,000 个日期时间字符串所需的时间。

有谁知道这样做的更快方法或加快方法的技巧?

castMethod1 takes 3673 ms 
castMethod2 takes 3812 ms 
castMethod3 takes 3931 ms

代码:
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, month, day, hour, minute, second);
}

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

——
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]:" ") ) );
}

不,Date.parse 默认不会处理破折号。我需要为日期时间字符串返回 null,例如 "0000-00-00" .

最佳答案

我一直在使用以下代码片段来解析 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;
}

只需删除时间部分,它应该可以满足您的需求:
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[2]) - 1, int(matches[3]));

    return d;
}

不知道速度,我在我的应用程序中没有担心过。在我的机器上在不到一秒的时间内完成了 50K 次迭代。

关于apache-flex - Actionscript 3 - 解析 yyyy-mm-dd hh :mm:ss to a Date object? 的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3163/

相关文章:

apache-flex - 在 flex 中向 XML 添加子节点

actionscript-3 - 如何在 AS3 中引用动态实例化对象? (在舞台上添加了 Moviclip)

java - 如何在Wowza服务器的publish方法中停止流媒体

xml - 使用 adobe air 保存 XML 文件会在开头创建虚假符号

flash - 如何检测视频何时缓冲?

apache-flex - Flex - 自动调整数据网格大小的问题

apache-flex - 如何以编程方式滚动到 mx :TextArea in Flex? 的底部

Java柏林噪声

actionscript-3 - 如何将多个 'Datas' 传递给 View ?

apache-flex - Adobe Air 应用程序能否关闭自签名证书警告?