/ Published in: ActionScript 3
Expand |
Embed | Plain Text
/* * Darron Schall ([email protected]) * August 27, 2003 * * Rob Sawyer ([email protected]) * February 7th, 2009 * Converted to AS3 and added timeAgoInWords(); * timeAgoInWords was converted from the CakePHP method * * ActionScript port of ColdFusion's DateFormat function. * * @param theDate - a Flash Date Object * @param format - see http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/functi59.htm for more information on valid formats * * Revision History: * Rev Date Who Description * 1.0 8/27/03 darron Initial Release * 1.1 11/10/05 john Static Class conversion of Darron Schalls Date Formatter * * -------------------------------------- * License For Use * -------------------------------------- * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package com.wdts.utils{ public class DateFormatter { public function DateFormatter() {} static public function formatTo(theDate:Date, mask:String):String { var months:Array = new Array(); var days:Array = new Array(); months["Jan"] = {m:1, n:"January"}; months["Feb"] = {m:2, n:"February"}; months["Mar"] = {m:3, n:"March"}; months["Apr"] = {m:4, n:"April"}; months["May"] = {m:5, n:"May"}; months["Jun"] = {m:6, n:"June"}; months["Jul"] = {m:7, n:"July"}; months["Aug"] = {m:8, n:"August"}; months["Sep"] = {m:9, n:"September"}; months["Oct"] = {m:10, n:"October"}; months["Nov"] = {m:11, n:"November"}; months["Dec"] = {m:12, n:"December"}; days["Sun"] = {m:1, n:"Sunday"}; days["Mon"] = {m:1, n:"Monday"}; days["Tue"] = {m:1, n:"Tuesday"}; days["Wed"] = {m:1, n:"Wednesday"}; days["Thu"] = {m:1, n:"Thursday"}; days["Fri"] = {m:1, n:"Friday"}; days["Sat"] = {m:1, n:"Saturday"}; // verify Date object being sent if (!(theDate is Date)) { // trace("Error in dateFormat - first parameter must be a date object"); return "Error -- Date Object missing"; } var parts = theDate.toString().split(" "); var dayOfWeek:String = parts[0]; var month:String = parts[1]; var day:String = parts[2]; var year:String = parts[5]; var retString:String = ""; // search for the mask words and replace with the appropriate mask if (mask.indexOf("short") != -1) { mask = mask.split("short").join("m/d/y"); } else if (mask.indexOf("medium") != -1) { mask = mask.split("medium").join("mmm d, yyyy"); } else if (mask.indexOf("long") != -1) { mask = mask.split("long").join("mmmm d, yyyy"); } else if (mask.indexOf("full") != -1) { mask = mask.split("full").join("dddd, mmmm d, yyyy"); } // used to store what character set we're processing var currentlyProcessing:String = ''; // how many of the characters have we run into? var count:Number = 0; // loop through the format and replace values when we can for (var i:Number = 0; i < mask.length; i++) { switch (mask.charAt(i)) { case 'd': case 'm': case 'y': // if we've been processing one set of characters and // stumbled across a new set, we need to update // the return string if (currentlyProcessing != '') { if (currentlyProcessing != mask.charAt(i)) { // processing a new character, so figure out what we've // been processing, update the processing character, // and re-set the count retString += maskReplace(currentlyProcessing, count, dayOfWeek, month, day, year, months, days); currentlyProcessing = mask.charAt(i); count = 0; } } else { currentlyProcessing = mask.charAt(i); } count++; break; default: // we're stumbled upong a character thats not a mask character // so if we've been processing something, replace it // for the return string and reset what we've processing // to nothing if (currentlyProcessing != '') { retString += maskReplace(currentlyProcessing, count, dayOfWeek, month, day, year, months, days); count = 0; currentlyProcessing = ''; } // just add the character we've run into to the return string retString += mask.charAt(i); } } // after we're done, we need to check to see if we're still processing anything if (count > 0) { retString += maskReplace(currentlyProcessing, count, dayOfWeek, month, day, year, months, days); } // finally, return the string with the mask replace with actual values return retString; } /* Darron Schall August 27, 2003 Private "helper" function for dateFormat. Not meant to be called directly. */ private static function maskReplace(which:*, count:*, dayOfWeek:*, month:*, day:*, year:*, months:*, days:*):*{ switch(which) { case 'd': switch (count) { case 1: return day; case 2: return (day<10) ? "0"+day : day; case 3: return dayOfWeek; case 4: return days[dayOfWeek].n; } break; case 'y': switch (count) { case 1: return parseInt(String(year).substr(2,2)); case 2: return String(year).substr(2,2); case 4: return year; } case 'm': switch (count) { case 1: return months[month].m; case 2: return (months[month].m<10) ? "0"+months[month].m : months[month].m; case 3: return month; case 4: return months[month].n; } } } /** * Handles converting the time to a nicename like "2 hours ago" * @param datetime * @param display_recent * @param format * @param recent_threshold * @param backwards */ static public function timeAgoInWords(date:String="1970-01-22",time:String="00:00:00",timezone:Number = -8 , format:String = "mm/dd/yy", backwards:Boolean = false, recent_threshold:Number = 60):String{ /** * Take special care to notice that month (4) is zero-based, meaning that January is 0, and December is 11. * Hour, the 4th parameter, starts with 0 as midnight, and ends with 23 as 11pm. The constructor is in the format * new Date(year, month, day, hours, minutes, seconds, milliseconds). */ //Parse the date trace("========= DATE ========== "); trace(" "+ date); var dateArray:Array = date.split("-",3); var dYear:Number = Number(dateArray[0]); var dMonth:Number = Number(dateArray[1])-1; var dDay:Number = Number(dateArray[2]); // trace(" year: " + dateArray[0]); trace(" month: " + dateArray[1]); trace(" day: " + dateArray[2]); var timeArray:Array = time.split(":"); var dMin:Number = Number(timeArray[1]); var dHour:Number = Number(timeArray[0]); var meridian:String; if(dHour > 23){ meridian = "PM"; dHour = 12; }else{ meridian = "AM"; } //dHour %= 24; var dSec:Number = Number(timeArray[2]); trace(" min: " + dMin); trace(" hour: " + dHour); trace(" sec: " + dSec); var datetime:Date = new Date(); trace(" timezone: " + timezone); //datetime = DateUtility.ChangeTimezone(datetime, timezone); datetime.setUTCFullYear(dYear,dMonth,dDay); datetime.setUTCHours(dHour,dMin,dSec,0); //var datetime:Date = new Date(dMonth+"/"+dDay+"/"+dYear+" "+time + " "+meridian); trace(" "+datetime+" "); trace("========================= "); var in_seconds:Number = datetime.getTime()/1000; //Get the Date in seconds var now:Date = new Date(); var diff:Number; var months:Number; var weeks:Number; var days:Number; var hours:Number; var minutes:Number; var seconds:Number; //var secondsSince:Number = Math.floor(now.time); //The number of seconds since midnight January 1, 1970, universal time, for a Date object. //trace(" Seconds since January 1, 1970 -> " + secondsSince); var secondsSince:Number = now.getTime()/1000; //Get the Date in seconds if (backwards) { diff = in_seconds - secondsSince; } else { diff = secondsSince - in_seconds; } var dif:Number = diff; months = Math.floor(dif / 2419200); dif -= months * 2419200; weeks = Math.floor(dif / 604800); dif -= weeks * 604800; days = Math.floor(dif / 86400); dif -= days * 86400; hours = Math.floor(dif / 3600); dif -= hours * 3600; minutes = Math.floor(dif / 60); dif -= minutes * 60; seconds = dif; var old:Boolean; if (months > 0) { // over a month old, just show date (mm/dd/yyyy format) //trace("format: " + format); var relative_date:String = 'on ' + formatTo(datetime,format); trace("=== FORMAT -> " + formatTo(datetime,format)); old = true; } else { relative_date = ''; old = false; if (weeks > 0) { // weeks and days relative_date += (relative_date ? ', ' : '') + weeks + ' week' + (weeks > 1 ? 's' : ''); relative_date += days > 0 ? (relative_date ? ', ' : '') + days + ' day' + (days > 1 ? 's' : '') : ''; } else if(days > 0) { // days and hours relative_date += (relative_date ? ', ' : '') + days + ' day' + (days > 1 ? 's' : ''); relative_date += hours > 0 ? (relative_date ? ', ' : '') + hours + ' hour' + (hours > 1 ? 's' : '') : ''; } else if(hours > 0) { // hours and minutes relative_date += (relative_date ? ', ' : '') + hours + ' hour' + (hours > 1 ? 's' : ''); relative_date += minutes > 0 ? (relative_date ? ', ' : '') + minutes + ' minute' + (minutes > 1 ? 's' : '') : ''; } else if(minutes > 0) { // minutes only relative_date += (relative_date ? ', ' : '') + minutes + ' minute' + (minutes > 1 ? 's' : ''); } else { // seconds only relative_date += (relative_date ? ', ' : '') + Math.round(seconds) + ' second' + (seconds != 1 ? 's' : ''); } } var ret:String = relative_date; // show relative date and add proper verbiage if (!backwards && !old) { ret += ' ago'; } /*if(display_recent) { if(dif<=recent_threshold) { ret = '<span class="recent">'+ret+'</span>'; } }*/ return ret; //return formatTo(datetime,format) + " " +time; } } }
You need to login to post a comment.
