AS3 检查日期是否属于范围?
AS3 check if date belongs to the range?
我想检查给定日期是否属于两个给定日期。
日期采用字符串格式,如“2015-02-19”
首先你需要解析字符串到日期。您可以为此使用 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;
}
如果所有日期的格式都为 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
我想检查给定日期是否属于两个给定日期。 日期采用字符串格式,如“2015-02-19”
首先你需要解析字符串到日期。您可以为此使用 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;
}
如果所有日期的格式都为 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