Time conversion using the proxy class

August 1, 2008 – 12:18 pm

I’m quite a fan of neat, sparse code, especially if efficiency isn’t so important. Following on from my date stuff earlier, I had to have a few conversion utils, including time conversions. Everyone’s been through the boredom of creating the methods for millisecondsToSeconds, secondsToMinutes, minutesToHours and so on, and then making composite functions to jump from seconds to hours or whatever, but it’s a pretty dull process.

Using a simple implementation of the proxy class, the following takes whatever combination you like of unitToUnit from milliseconds, seconds, minutes, hours, days and weeks, and automatically works it out. So while, due to the nature of extending proxies, it’s by no means efficient, it’s definitely elegant, and could be easily adapted for similarly incremental units, eg bytes & bits.

package com.utils {

 /**
  * @author chris@acleveraddress.com
  */

 import flash.utils.Proxy;
 import flash.utils.flash_proxy;

 dynamic public class TimeUtil extends Proxy {

  private var units : Array = [
   ["weeks",7],
   ["days",24],
   ["hours",60],
   ["minutes",60],
   ["seconds",1000],
   ["milliseconds"]
  ];

  public function TimeUtil() {
  }

  override flash_proxy function callProperty(name : *, ...args : *) : * {
   var arr : Array = String(name).toLowerCase().split("to");
   var from : uint = indexOfMulti(units, arr[0]);
   var to : uint = indexOfMulti(units, arr[1]);
   var i : Number = args[0];

   while (from != to) {
    if (to > from) {
     i *= units[from++][1];
    } else {
     i /= units[--from][1];
    }
   }

   return i;
  }

  private function indexOfMulti(arr : Array, str : String) : int {
   for each (var a : Array in arr) {
    if (a[0] == str) return arr.indexOf(a);
   }
   throw('Function badly named');
  }
 }
}

Usage:

var tu : TimeUtil = new TimeUtil();
trace(tu.millisecondsToWeeks(604800000));

Post a Comment

Enter this code