views:

301

answers:

3

Hi I need to be able to subtract 2hrs ,8hrs, 1 day and 1 week from the current Date.

Then convert to yyy-mm-dd hh:mm:ss format.

So far I have been unsuccessful.

What is the proper method to do this in actionscript?

+1  A: 

Hi there eco_bach,

There are a few options here, but I think the simplest solution in your case is to work with milliseconds. You can use += and -= to modify the current millisecond value of the date. The trickiest thing is the conversion of your values to milliseconds. Here are a few examples:

var myDate:Date; //assuming this is a actual date value.

//subtract 2 hrs
var twoHoursInMilliseconds:int = 2 * 60 * 60 * 1000; //2 hours * 60 minutes * 60 seconds * 1000 milliseconds (in a second)
myDate.milliseconds -= twoHoursInMilliseconds;

//subtract 1 day
var oneDayInMilliseconds:int = 1 *24 * 60 * 60 * 1000;
myDate.milliseconds -= oneDayInMilliseconds;

For formating, you will want to use this methods:

trace(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());

Hopefully that points you in the right direction,

Happy Coding!

Edit: Updated code to fix bug.

Tyler Egeto
Thanks Tyler.I was wondering if I also need to modify the milliseoconds value to get local time. If I use Date.parse to get milliseconds I believe it returns UTCtime.
eco_bach
Check out the docs, there is a millisecondsUTC property
Tyler Egeto
Another caveat Tyler, not possible to subtract milliseconds from a Date object as far as I know. What I did was convert first to milliseconds using the static valueOf method ie 'dateObject.valueOf()Then create a new date and set the value of this new date object using the previously converted milliseconds value.
eco_bach
Oops that is a typo, it should have been: myDate.milliseconds -= oneDayInMilliseconds; Sorry!
Tyler Egeto
A: 

Hi Eco, I will agree with Tyler for his approach to work with date in the form of miliseconds. For conversion, you may also like to use DateFormatter as below.

var dateFormatter:DateFormatter = new DateFormatter(); dateFormatter.formatString = 'yyy-mm-dd hh:mm:ss' ; var formattedDate:String = dateFormatter.format(d); trace(formattedDate);

Wishes, Ashine.

Ashine
I don't think their using Flex, but that would be the ideal formatting solution if they are!
Tyler Egeto
A: 

Just change the UTC values of the date/hour.

var d:Date = new Date();
d.dateUTC -= 1; //subtract one day
d.hoursUTC -= 1; //subtract one hour

and then trace the output using Tyler's trace statement.

trace(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());

For more information on the Date class, check out http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Date.html

washwithcare