Flex中字符串String按照格式转化为日期Date的方法

在Flex中,要通过传入时间的字符串和格式字符串的方式来转换出Date,Flex本身没有完善的方法,不知道Adobe在想什么,这么简单实用的功能都没有.(回想起来,还是java神马的好)

在网上找了好久都没有完善的解决方案,最后偶然发现DateField带着一个StringToDate的静态方法,但是只支持"年月日"的日期格式,不支持"时分秒"等的时间格式,于是对其功能进行了扩展.

闲话不多扯,下面是源代码,拿去直接可以用.

目前只扩展到了对"年月日时分秒".

ActionScript:

 

public function string2Date(valueString:String, inputFormat:String):Date
{
	var mask:String
	var temp:String;
	var dateString:String = "";
	var monthString:String = "";
	var yearString:String = "";
	var hourString:String = "";
	var minuteString:String = "";
	var secondString:String = "";
	var j:int = 0;
	
	var n:int = inputFormat.length;
	for (var i:int = 0; i < n; i++,j++)
	{
		temp = "" + valueString.charAt(j);
		mask = "" + inputFormat.charAt(i);
		
		if (mask == "M")
		{
			if (isNaN(Number(temp)) || temp == " ")
				j--;
			else
				monthString += temp;
		}
		else if (mask == "D")
		{
			if (isNaN(Number(temp)) || temp == " ")
				j--;
			else
				dateString += temp;
		}
		else if (mask == "Y")
		{
			yearString += temp;
		}
		else if(mask=="J")
		{
			if (isNaN(Number(temp)) || temp == " ")
				j--;
			else
				hourString += temp;
		}
		else if(mask=="N")
		{
			if (isNaN(Number(temp)) || temp == " ")
				j--;
			else
				minuteString += temp;
		}
		else if(mask=="S")
		{
			if (isNaN(Number(temp)) || temp == " ")
				j--;
			else
				secondString += temp;
		}
		else if (!isNaN(Number(temp)) && temp != " ")
		{
			return null;
		}
	}
	
	temp = "" + valueString.charAt(inputFormat.length - i + j);
	if (!(temp == "") && (temp != " "))
		return null;
	
	var monthNum:Number = Number(monthString);
	var dayNum:Number = Number(dateString);
	var yearNum:Number = Number(yearString);
	var hourNum:Number = Number(hourString);
	var minuteNum:Number = Number(minuteString);//如果字符串为空会转换成0
	var secondNum:Number = Number(secondString);
	if (isNaN(yearNum) || isNaN(monthNum) || isNaN(dayNum))
		return null;
	
	if (yearString.length == 2 && yearNum < 70)
		yearNum+=2000;
	
	var newDate:Date = new Date(yearNum, monthNum - 1, dayNum,hourNum,minuteNum,secondNum);
	
	if (dayNum != newDate.getDate() || (monthNum - 1) != newDate.getMonth())
		return null;
	
	return newDate;
}

 

你可能感兴趣的:(Date,字符串,String,Flex,日期)