index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. function padWithZeros(vNumber, width) {
  3. var numAsString = vNumber.toString();
  4. while (numAsString.length < width) {
  5. numAsString = '0' + numAsString;
  6. }
  7. return numAsString;
  8. }
  9. function addZero(vNumber) {
  10. return padWithZeros(vNumber, 2);
  11. }
  12. /**
  13. * Formats the TimeOffset
  14. * Thanks to http://www.svendtofte.com/code/date_format/
  15. * @private
  16. */
  17. function offset(timezoneOffset) {
  18. // Difference to Greenwich time (GMT) in hours
  19. var os = Math.abs(timezoneOffset);
  20. var h = String(Math.floor(os / 60));
  21. var m = String(os % 60);
  22. if (h.length === 1) {
  23. h = '0' + h;
  24. }
  25. if (m.length === 1) {
  26. m = '0' + m;
  27. }
  28. return timezoneOffset < 0 ? '+' + h + m : '-' + h + m;
  29. }
  30. function asString(format, date, timezoneOffset) {
  31. if (typeof format !== 'string') {
  32. timezoneOffset = date;
  33. date = format;
  34. format = module.exports.ISO8601_FORMAT;
  35. }
  36. if (!date) {
  37. date = new Date();
  38. }
  39. // make the date independent of the system timezone by working with UTC
  40. if (timezoneOffset === undefined) {
  41. timezoneOffset = date.getTimezoneOffset();
  42. }
  43. date.setUTCMinutes(date.getUTCMinutes() - timezoneOffset);
  44. var vDay = addZero(date.getUTCDate());
  45. var vMonth = addZero(date.getUTCMonth() + 1);
  46. var vYearLong = addZero(date.getUTCFullYear());
  47. var vYearShort = addZero(date.getUTCFullYear().toString().substring(2, 4));
  48. var vYear = (format.indexOf('yyyy') > -1 ? vYearLong : vYearShort);
  49. var vHour = addZero(date.getUTCHours());
  50. var vMinute = addZero(date.getUTCMinutes());
  51. var vSecond = addZero(date.getUTCSeconds());
  52. var vMillisecond = padWithZeros(date.getUTCMilliseconds(), 3);
  53. var vTimeZone = offset(timezoneOffset);
  54. date.setUTCMinutes(date.getUTCMinutes() + timezoneOffset);
  55. var formatted = format
  56. .replace(/dd/g, vDay)
  57. .replace(/MM/g, vMonth)
  58. .replace(/y{1,4}/g, vYear)
  59. .replace(/hh/g, vHour)
  60. .replace(/mm/g, vMinute)
  61. .replace(/ss/g, vSecond)
  62. .replace(/SSS/g, vMillisecond)
  63. .replace(/O/g, vTimeZone);
  64. return formatted;
  65. }
  66. module.exports = asString;
  67. module.exports.asString = asString;
  68. module.exports.ISO8601_FORMAT = 'yyyy-MM-ddThh:mm:ss.SSS';
  69. module.exports.ISO8601_WITH_TZ_OFFSET_FORMAT = 'yyyy-MM-ddThh:mm:ss.SSSO';
  70. module.exports.DATETIME_FORMAT = 'dd MM yyyy hh:mm:ss.SSS';
  71. module.exports.ABSOLUTETIME_FORMAT = 'hh:mm:ss.SSS';