A few date manipulation functions for JS/AS…

Convert a MySQL DATE or DATETIME field into a valid JS/AS Date object:

UPDATE: Apparently FireFox can’t handle dashes when parsing the date. In the above replacement, use slashes instead:

Convert a JS Date Object to a MySQL formatted string

Get amount of time between two dates – returns object with milliseconds, seconds, minutes, hours, days and weeks:

Return true/false if a given date falls on a weekend:

Takes a given date and adds 1 day at a time until the date falls on a weekend. The second argument determines if the date should move backward (true) or backward (false, default):

Takes a given date and adds 1 day at a time until the date falls on a weekday. The second argument determines if the date should move backward (true) or backward (false, default):

All bundled up in a DateTools static utility class:

[as3]
package {

public class DateTools {

public function DateTools():void {
throw new Error("DateTools should not be instantiated.");
}

public static const MONTH_LABELS:Array = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];

public static const DAY_LABELS:Array = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];

public static function fromMySQL(date:String):Date {
date = date.replace(/^(\d{4})-(\d{2})-(\d{2})/g, ‘$2-$3-$1’);
return new Date(date);
}

public static function timeBetween(from:Date, to:Date):Object {
var diff:uint = Math.abs(Math.floor(Number(from) – Number(to)));
return {
‘milliseconds’ : diff,
‘seconds’ : diff / 1000,
‘minutes’ : diff / 60000,
‘hours’ : diff / 360000,
‘days’ : diff / 86400000,
‘weeks’ : diff / 604800000
}
}

public static function isWeekend(date:Date):Boolean {
return Boolean(date.getDay() % 6);
}

public static function moveToWeekend(date:Date, increase:Boolean = true):Date {
var day:Number = date.getDate();
var increment:int = increase ? 1 : -1;
while (date.getDay() % 6 > 1) date.setDate(day += increment);
return date;
}
public static function moveOffWeekend(date:Date, increase:Boolean = true):Date {
var day:Number = date.getDate();
var increment:int = increase ? 1 : -1;
while (date.getDay() % 6 == 1) date.setDate(day += increment);
return date;
}

}

}
[/as3]