date_format.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. exports.ISO8601_FORMAT = "yyyy-MM-dd hh:mm:ss.SSS";
  3. exports.ISO8601_WITH_TZ_OFFSET_FORMAT = "yyyy-MM-ddThh:mm:ssO";
  4. exports.DATETIME_FORMAT = "dd MM yyyy hh:mm:ss.SSS";
  5. exports.ABSOLUTETIME_FORMAT = "hh:mm:ss.SSS";
  6. function padWithZeros(vNumber, width) {
  7. var numAsString = vNumber + "";
  8. while (numAsString.length < width) {
  9. numAsString = "0" + numAsString;
  10. }
  11. return numAsString;
  12. }
  13. function addZero(vNumber) {
  14. return padWithZeros(vNumber, 2);
  15. }
  16. /**
  17. * Formats the TimeOffest
  18. * Thanks to http://www.svendtofte.com/code/date_format/
  19. * @private
  20. */
  21. function offset(date) {
  22. // Difference to Greenwich time (GMT) in hours
  23. var os = Math.abs(date.getTimezoneOffset());
  24. var h = String(Math.floor(os/60));
  25. var m = String(os%60);
  26. if (h.length == 1) {
  27. h = "0" + h;
  28. }
  29. if (m.length == 1) {
  30. m = "0" + m;
  31. }
  32. return date.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
  33. }
  34. exports.asString = function(/*format,*/ date) {
  35. var format = exports.ISO8601_FORMAT;
  36. if (typeof(date) === "string") {
  37. format = arguments[0];
  38. date = arguments[1];
  39. }
  40. var vDay = addZero(date.getDate());
  41. var vMonth = addZero(date.getMonth()+1);
  42. var vYearLong = addZero(date.getFullYear());
  43. var vYearShort = addZero(date.getFullYear().toString().substring(3,4));
  44. var vYear = (format.indexOf("yyyy") > -1 ? vYearLong : vYearShort);
  45. var vHour = addZero(date.getHours());
  46. var vMinute = addZero(date.getMinutes());
  47. var vSecond = addZero(date.getSeconds());
  48. var vMillisecond = padWithZeros(date.getMilliseconds(), 3);
  49. var vTimeZone = offset(date);
  50. var formatted = format
  51. .replace(/dd/g, vDay)
  52. .replace(/MM/g, vMonth)
  53. .replace(/y{1,4}/g, vYear)
  54. .replace(/hh/g, vHour)
  55. .replace(/mm/g, vMinute)
  56. .replace(/ss/g, vSecond)
  57. .replace(/SSS/g, vMillisecond)
  58. .replace(/O/g, vTimeZone);
  59. return formatted;
  60. };