AS3检查日期是否属于该范围?

时间:2015-02-19 08:40:26

标签: android actionscript-3 air

如果给定日期属于两个给定日期,我想检查一下。 日期采用字符串格式,如" 2015-02-19"

2 个答案:

答案 0 :(得分:1)

首先,你需要解析字符串到目前为止。您可以使用RegExp。模式将如下所示:/(\d\d\d\d)-(\d\d)-(\d\d)/。一年四位数,一个月两个,一天两个。接下来,看看我的代码。如果问题不明确,请询问。

var begDateStr:String = "2015-02-19";
var midDateStr:String = "2015-04-19";
var endDateStr:String = "2015-06-19";

var begDate:Date = parseDate(begDateStr);
var midDate:Date = parseDate(midDateStr);
var endDate:Date = parseDate(endDateStr);

if (endDate > midDate && begDate < midDate)
{
    trace("OK");
}

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

答案 1 :(得分:1)

如果您的所有日期都格式化为YYYY-MM-DD,则它们是按字母顺序排列的,因此您可以使用常规比较运算符(<>==来比较字符串, <=>=),because when both operands are strings they are compared alphabetically

所以你可以这样做:

var from:String = "2015-02-02";
var to:String = "2015-06-06";

function check(date:String):Boolean {
    return date >= from && date <= to;
}

check("2015-05-05"); // true
check("2015-01-01"); // false
check("2015-07-05"); // false
check("2014-05-05"); // false
// etc