最近flex项目中用到了关于日期时间的计算,也从网上找了些资料。自己整理了一下,方便以后查询
1.计算一个月的最后一天:
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" initialize="application1_initializeHandler(event)" > <s:layout> <s:BasicLayout/> </s:layout> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <fx:Script> <![CDATA[ import mx.controls.Alert; import mx.events.FlexEvent; import mx.states.SetStyle; private function computeFinalDay():void{ var nowDate:Date = new Date(); var nowyear:String = nowDate.getFullYear().toString(); var nowmonth:String = (nowDate.getMonth()+1).toString().length == 1?"0"+(nowDate.getMonth()+1).toString():(nowDate.getMonth()+1).toString(); var lastdaysOfMonth:String = daysOfMonth(nowyear+nowmonth); Alert.show("当月最后一天"+lastdaysOfMonth); } public function daysOfMonth(Month:String):String{ var currentMonth:Date = new Date(Month.substring(0,4), Month.substring(4,6), 1); var lastMonth:Date = new Date(Month.substring(0,4), String(Number(Month.substring(4,6))-1), 1); var diffDays:Number = currentMonth.valueOf() - lastMonth.valueOf(); return currentMonth.getMonth()+"-"+(diffDays/( 24 * 60 * 60 * 1000)); } /** * 初始化函数 * 作者: * 日期: * **/ protected function application1_initializeHandler(event:FlexEvent):void { computeFinalDay(); } ]]> </fx:Script> </s:Application>
//计算当前日期的前一天
var date1:Date ; var date2:Date; var num1:Number =date1.valueOf(); var num2:Number =date2.valueOf(); var different:Number = num2-num1; var diffDay:int = int(diff/24/60/60/1000);//方法1 var d1Days : int = int(num1/ 24 / 60 / 60 / 1000); var d2Days : int = int(num2/ 24 / 60 / 60 / 1000);
private function dateAdd(datepart:String="", number:Number=0, date:Date=null):Date { if (date == null) { date=new Date(); } var returnDate:Date=new Date(date.time); switch (datepart.toLowerCase()) { case "fullyear": case "month": case "date": case "hours": case "minutes": case "seconds": case "milliseconds": returnDate[datepart]+=number; break; default: break; } var newdate:Date=new Date(returnDate.getFullYear(), returnDate.getMonth(), returnDate.date - 1); return newdate; }
//给定的日期上加一天 private function addOneDay(day:int, mydate:Date):Date { var returnDate:Date = new Date(mydate.time); returnDate['date'] += day //day就是你要加的天数,如果是加1天则为1,如果是减天则为-1 return returnDate; }