Posted By

adrianparr on 07/08/11


Tagged

time parse date format utc timestamp formatted hours minutes as3 backend hrs mins dirty


Versions (?)

AS3 Get formatted time from dirty timestamp string


 / Published in: ActionScript 3
 

I was working on a project where the timestamp string I was getting from the backend developer was pretty dirty in the way it was formatted. For example, it looked like "/Date(1310127448000+0100)/". I needed to get a nicely formatted time from it in the format hrs:mins

  1. var timestampFromBackend:String = "/Date(1310127448000+0100)/";
  2. trace("timestampFromBackend: " + timestampFromBackend);
  3. var formattedTime:String = formatedTimeFromTimestamp(timestampFromBackend);
  4. trace("formattedTime: " + formattedTime);
  5.  
  6. function formatedTimeFromTimestamp(str:String):String {
  7. /*
  8. Might get passed something like this ...
  9. /Date(1310127448000+0100)/
  10. but it also works if you are passed ...
  11. 1310127448000+0100
  12. */
  13.  
  14. var openBracketIndex:int;
  15. var closeBracketIndex:int;
  16.  
  17. if (str.indexOf("(") != -1) {
  18. openBracketIndex = str.indexOf("(");
  19. } else {
  20. openBracketIndex = -1;
  21. }
  22. if (str.indexOf(")") != -1) {
  23. closeBracketIndex = str.indexOf(")");
  24. } else {
  25. closeBracketIndex = str.length;
  26. }
  27.  
  28. str = str.substring(openBracketIndex + 1, closeBracketIndex);
  29. var arr:Array = new Array();
  30. if (str.indexOf("+") != -1) {
  31. arr = str.split("+");
  32. str = arr[0];
  33. } else if (str.indexOf("-") != -1) {
  34. arr = str.split("-");
  35. str = arr[0];
  36. }
  37.  
  38. var timestampDate:Date = new Date(Number(str));
  39. var hrs:String = String(timestampDate.getHours());
  40. if (hrs.length < 2) {
  41. hrs = "0" + hrs;
  42. }
  43. var mins:String = String(timestampDate.getMinutes());
  44. if (mins.length < 2) {
  45. mins = "0" + mins;
  46. }
  47.  
  48. str = hrs + ":" + mins;
  49. return str;
  50. }
  51.  
  52. // OUTPUT
  53. // timestampFromBackend: /Date(1310127448000+0100)/
  54. // formattedTime: 13:17

Report this snippet  

You need to login to post a comment.