How can I get the current number of milliseconds since midnight January 1, 1970 in AS3 without having to use the 'new' operator? I'm asking because I need to do this about 100 times per second and currently try to reduce heap allocations to keep gc low.
You should create it once and then add milliseconds, that passed since that creation with getTimer(); You will also need a helping variable to store your Data creation time;
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.getTimer;
public class Main extends Sprite
{
private var _myLittleDate:Date;
private var _myLittleDateCreationTime:Number;
public function Main():void
{
_myLittleDate = new Date(); //Our first and only object creation
_myLittleDateCreationTime = getTimer(); //Store it's creation time
addEventListener(Event.ENTER_FRAME, onEnterFrame); //Check function
}
private function onEnterFrame(e:Event):void
{
_myLittleDate.time += ( getTimer() - _myLittleDateCreationTime );
trace(_myLittleDate); //You get valid, refreshed data object here
_myLittleDateCreationTime = getTimer(); // Don't forget to update your initial time
//It's accurate since method .getTimer() is accurate itself
//You can even compare two Data object by creating another and tracing it right here
}
}
}
If you need just to know what time has passed since last frame, without knowing the day of the week, or a year, you can just use getTimer(); on it's own, it's more efficient
Util method that I use:
// Get time since the epoch and time since the VM was started
private static const dateTime:Number = new Date().time;
private static const dateTimestamp:uint = getTimer();
/**
* Current time in ms
*/
public static function getCurrentTime():Number
{
return dateTime + (getTimer() - dateTimestamp);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With