Posted By

robksawyer on 03/03/09


Tagged

date utility


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

zimmen
zeman
Pingpongbal
iamgowan
TrentSkunk


DateUtility


 / Published in: ActionScript 3
 

  1. /*
  2. * Darron Schall ([email protected])
  3. * August 27, 2003
  4. *
  5. * Rob Sawyer ([email protected])
  6. * February 7th, 2009
  7. * Converted to AS3 and added timeAgoInWords();
  8. * timeAgoInWords was converted from the CakePHP method
  9. *
  10. * ActionScript port of ColdFusion's DateFormat function.
  11. *
  12. * @param theDate - a Flash Date Object
  13. * @param format - see http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/functi59.htm for more information on valid formats
  14. *
  15. * Revision History:
  16. * Rev Date Who Description
  17. * 1.0 8/27/03 darron Initial Release
  18. * 1.1 11/10/05 john Static Class conversion of Darron Schalls Date Formatter
  19. *
  20. * --------------------------------------
  21. * License For Use
  22. * --------------------------------------
  23. * Redistribution and use in source and binary forms, with or without modification,
  24. * are permitted provided that the following conditions are met:
  25. *
  26. * 1. Redistributions of source code must retain the above copyright notice, this
  27. * list of conditions and the following disclaimer.
  28. *
  29. * 2. Redistributions in binary form must reproduce the above copyright notice,
  30. * this list of conditions and the following disclaimer in the documentation
  31. * and/or other materials provided with the distribution.
  32. *
  33. * 3. The name of the author may not be used to endorse or promote products derived
  34. * from this software without specific prior written permission.
  35. *
  36. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  38. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  39. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  40. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  41. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  42. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  43. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  44. * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  45. * OF SUCH DAMAGE.
  46. */
  47.  
  48. package com.wdts.utils{
  49.  
  50. public class DateFormatter {
  51.  
  52. public function DateFormatter() {}
  53.  
  54. static public function formatTo(theDate:Date, mask:String):String {
  55.  
  56. var months:Array = new Array();
  57. var days:Array = new Array();
  58.  
  59. months["Jan"] = {m:1, n:"January"};
  60. months["Feb"] = {m:2, n:"February"};
  61. months["Mar"] = {m:3, n:"March"};
  62. months["Apr"] = {m:4, n:"April"};
  63. months["May"] = {m:5, n:"May"};
  64. months["Jun"] = {m:6, n:"June"};
  65. months["Jul"] = {m:7, n:"July"};
  66. months["Aug"] = {m:8, n:"August"};
  67. months["Sep"] = {m:9, n:"September"};
  68. months["Oct"] = {m:10, n:"October"};
  69. months["Nov"] = {m:11, n:"November"};
  70. months["Dec"] = {m:12, n:"December"};
  71.  
  72. days["Sun"] = {m:1, n:"Sunday"};
  73. days["Mon"] = {m:1, n:"Monday"};
  74. days["Tue"] = {m:1, n:"Tuesday"};
  75. days["Wed"] = {m:1, n:"Wednesday"};
  76. days["Thu"] = {m:1, n:"Thursday"};
  77. days["Fri"] = {m:1, n:"Friday"};
  78. days["Sat"] = {m:1, n:"Saturday"};
  79.  
  80. // verify Date object being sent
  81. if (!(theDate is Date)) {
  82. // trace("Error in dateFormat - first parameter must be a date object");
  83. return "Error -- Date Object missing";
  84. }
  85.  
  86. var parts = theDate.toString().split(" ");
  87. var dayOfWeek:String = parts[0];
  88. var month:String = parts[1];
  89. var day:String = parts[2];
  90. var year:String = parts[5];
  91.  
  92. var retString:String = "";
  93.  
  94. // search for the mask words and replace with the appropriate mask
  95. if (mask.indexOf("short") != -1) {
  96. mask = mask.split("short").join("m/d/y");
  97. } else if (mask.indexOf("medium") != -1) {
  98. mask = mask.split("medium").join("mmm d, yyyy");
  99. } else if (mask.indexOf("long") != -1) {
  100. mask = mask.split("long").join("mmmm d, yyyy");
  101. } else if (mask.indexOf("full") != -1) {
  102. mask = mask.split("full").join("dddd, mmmm d, yyyy");
  103. }
  104.  
  105. // used to store what character set we're processing
  106. var currentlyProcessing:String = '';
  107. // how many of the characters have we run into?
  108. var count:Number = 0;
  109.  
  110. // loop through the format and replace values when we can
  111. for (var i:Number = 0; i < mask.length; i++) {
  112. switch (mask.charAt(i)) {
  113. case 'd':
  114. case 'm':
  115. case 'y':
  116. // if we've been processing one set of characters and
  117. // stumbled across a new set, we need to update
  118. // the return string
  119. if (currentlyProcessing != '') {
  120. if (currentlyProcessing != mask.charAt(i)) {
  121. // processing a new character, so figure out what we've
  122. // been processing, update the processing character,
  123. // and re-set the count
  124. retString += maskReplace(currentlyProcessing, count, dayOfWeek, month, day, year, months, days);
  125. currentlyProcessing = mask.charAt(i);
  126. count = 0;
  127. }
  128. } else {
  129. currentlyProcessing = mask.charAt(i);
  130. }
  131. count++;
  132. break;
  133.  
  134. default:
  135. // we're stumbled upong a character thats not a mask character
  136. // so if we've been processing something, replace it
  137. // for the return string and reset what we've processing
  138. // to nothing
  139. if (currentlyProcessing != '') {
  140. retString += maskReplace(currentlyProcessing, count, dayOfWeek, month, day, year, months, days);
  141. count = 0;
  142. currentlyProcessing = '';
  143. }
  144. // just add the character we've run into to the return string
  145. retString += mask.charAt(i);
  146. }
  147. }
  148.  
  149. // after we're done, we need to check to see if we're still processing anything
  150. if (count > 0) {
  151. retString += maskReplace(currentlyProcessing, count, dayOfWeek, month, day, year, months, days);
  152. }
  153.  
  154. // finally, return the string with the mask replace with actual values
  155. return retString;
  156.  
  157.  
  158. }
  159.  
  160. /*
  161. Darron Schall
  162. August 27, 2003
  163.  
  164. Private "helper" function for dateFormat. Not meant to be called directly.
  165. */
  166. private static function maskReplace(which:*, count:*, dayOfWeek:*, month:*, day:*, year:*, months:*, days:*):*{
  167. switch(which) {
  168. case 'd':
  169. switch (count) {
  170. case 1: return day;
  171. case 2: return (day<10) ? "0"+day : day;
  172. case 3: return dayOfWeek;
  173. case 4: return days[dayOfWeek].n;
  174. }
  175. break;
  176. case 'y':
  177. switch (count) {
  178. case 1: return parseInt(String(year).substr(2,2));
  179. case 2: return String(year).substr(2,2);
  180. case 4: return year;
  181. }
  182.  
  183. case 'm':
  184. switch (count) {
  185. case 1: return months[month].m;
  186. case 2: return (months[month].m<10) ? "0"+months[month].m : months[month].m;
  187. case 3: return month;
  188. case 4: return months[month].n;
  189. }
  190. }
  191. }
  192.  
  193.  
  194. /**
  195. * Handles converting the time to a nicename like "2 hours ago"
  196. * @param datetime
  197. * @param display_recent
  198. * @param format
  199. * @param recent_threshold
  200. * @param backwards
  201. */
  202. 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{
  203.  
  204. /**
  205. * Take special care to notice that month (4) is zero-based, meaning that January is 0, and December is 11.
  206. * Hour, the 4th parameter, starts with 0 as midnight, and ends with 23 as 11pm. The constructor is in the format
  207. * new Date(year, month, day, hours, minutes, seconds, milliseconds).
  208. */
  209. //Parse the date
  210. trace("========= DATE ========== ");
  211. trace(" "+ date);
  212. var dateArray:Array = date.split("-",3);
  213. var dYear:Number = Number(dateArray[0]);
  214. var dMonth:Number = Number(dateArray[1])-1;
  215. var dDay:Number = Number(dateArray[2]);
  216. //
  217. trace(" year: " + dateArray[0]);
  218. trace(" month: " + dateArray[1]);
  219. trace(" day: " + dateArray[2]);
  220.  
  221. var timeArray:Array = time.split(":");
  222. var dMin:Number = Number(timeArray[1]);
  223. var dHour:Number = Number(timeArray[0]);
  224. var meridian:String;
  225. if(dHour > 23){
  226. meridian = "PM";
  227. dHour = 12;
  228. }else{
  229. meridian = "AM";
  230. }
  231. //dHour %= 24;
  232. var dSec:Number = Number(timeArray[2]);
  233. trace(" min: " + dMin);
  234. trace(" hour: " + dHour);
  235. trace(" sec: " + dSec);
  236.  
  237. var datetime:Date = new Date();
  238. trace(" timezone: " + timezone);
  239. //datetime = DateUtility.ChangeTimezone(datetime, timezone);
  240. datetime.setUTCFullYear(dYear,dMonth,dDay);
  241. datetime.setUTCHours(dHour,dMin,dSec,0);
  242.  
  243. //var datetime:Date = new Date(dMonth+"/"+dDay+"/"+dYear+" "+time + " "+meridian);
  244. trace(" "+datetime+" ");
  245. trace("========================= ");
  246. var in_seconds:Number = datetime.getTime()/1000; //Get the Date in seconds
  247. var now:Date = new Date();
  248. var diff:Number;
  249. var months:Number;
  250. var weeks:Number;
  251. var days:Number;
  252. var hours:Number;
  253. var minutes:Number;
  254. var seconds:Number;
  255.  
  256. //var secondsSince:Number = Math.floor(now.time); //The number of seconds since midnight January 1, 1970, universal time, for a Date object.
  257. //trace(" Seconds since January 1, 1970 -> " + secondsSince);
  258. var secondsSince:Number = now.getTime()/1000; //Get the Date in seconds
  259. if (backwards) {
  260. diff = in_seconds - secondsSince;
  261. } else {
  262. diff = secondsSince - in_seconds;
  263. }
  264.  
  265. var dif:Number = diff;
  266. months = Math.floor(dif / 2419200);
  267. dif -= months * 2419200;
  268. weeks = Math.floor(dif / 604800);
  269. dif -= weeks * 604800;
  270. days = Math.floor(dif / 86400);
  271. dif -= days * 86400;
  272. hours = Math.floor(dif / 3600);
  273. dif -= hours * 3600;
  274. minutes = Math.floor(dif / 60);
  275. dif -= minutes * 60;
  276. seconds = dif;
  277.  
  278. var old:Boolean;
  279. if (months > 0) {
  280. // over a month old, just show date (mm/dd/yyyy format)
  281. //trace("format: " + format);
  282. var relative_date:String = 'on ' + formatTo(datetime,format);
  283. trace("=== FORMAT -> " + formatTo(datetime,format));
  284. old = true;
  285. } else {
  286. relative_date = '';
  287. old = false;
  288.  
  289. if (weeks > 0) {
  290. // weeks and days
  291. relative_date += (relative_date ? ', ' : '') + weeks + ' week' + (weeks > 1 ? 's' : '');
  292. relative_date += days > 0 ? (relative_date ? ', ' : '') + days + ' day' + (days > 1 ? 's' : '') : '';
  293. } else if(days > 0) {
  294. // days and hours
  295. relative_date += (relative_date ? ', ' : '') + days + ' day' + (days > 1 ? 's' : '');
  296. relative_date += hours > 0 ? (relative_date ? ', ' : '') + hours + ' hour' + (hours > 1 ? 's' : '') : '';
  297. } else if(hours > 0) {
  298. // hours and minutes
  299. relative_date += (relative_date ? ', ' : '') + hours + ' hour' + (hours > 1 ? 's' : '');
  300. relative_date += minutes > 0 ? (relative_date ? ', ' : '') + minutes + ' minute' + (minutes > 1 ? 's' : '') : '';
  301. } else if(minutes > 0) {
  302. // minutes only
  303. relative_date += (relative_date ? ', ' : '') + minutes + ' minute' + (minutes > 1 ? 's' : '');
  304. } else {
  305. // seconds only
  306. relative_date += (relative_date ? ', ' : '') + Math.round(seconds) + ' second' + (seconds != 1 ? 's' : '');
  307. }
  308. }
  309.  
  310. var ret:String = relative_date;
  311.  
  312. // show relative date and add proper verbiage
  313. if (!backwards && !old) {
  314. ret += ' ago';
  315. }
  316. /*if(display_recent) {
  317. if(dif<=recent_threshold) {
  318. ret = '<span class="recent">'+ret+'</span>';
  319. }
  320. }*/
  321.  
  322. return ret;
  323. //return formatTo(datetime,format) + " " +time;
  324. }
  325. }
  326. }

Report this snippet  

You need to login to post a comment.