test_formats.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var assert = require('assert');
  2. var _ = require('underscore');
  3. var dateFormat = require('../lib/dateformat');
  4. var expects = {
  5. 'default': 'Wed Nov 26 2014 13:19:44',
  6. 'shortDate': '11/26/14',
  7. 'mediumDate': 'Nov 26, 2014',
  8. 'longDate': 'November 26, 2014',
  9. 'fullDate': 'Wednesday, November 26, 2014',
  10. 'shortTime': '1:19 PM',
  11. 'mediumTime': '1:19:44 PM',
  12. 'longTime': '1:19:44 PM %TZ_PREFIX%%TZ_OFFSET%',
  13. 'isoDate': '2014-11-26',
  14. 'isoTime': '13:19:44',
  15. 'isoDateTime': '2014-11-26T13:19:44%TZ_OFFSET%',
  16. 'isoUtcDateTime': '',
  17. 'expiresHeaderFormat': 'Wed, 26 Nov 2014 13:19:44 %TZ_PREFIX%%TZ_OFFSET%'
  18. };
  19. function pad(num, size) {
  20. var s = num + '';
  21. while (s.length < size) {
  22. s = '0' + s;
  23. }
  24. return s;
  25. }
  26. function parseOffset(date) {
  27. var offset = date.getTimezoneOffset();
  28. var hours = Math.floor(-1 * offset / 60);
  29. var minutes = (-1 * offset) - (hours * 60);
  30. var sign = offset > 0 ? '-' : '+';
  31. return {
  32. offset: offset,
  33. hours: hours,
  34. minutes: minutes,
  35. sign: sign,
  36. };
  37. }
  38. function timezoneOffset(date) {
  39. var offset = parseOffset(date);
  40. return offset.sign + pad(offset.hours, 2) + pad(offset.minutes, 2);
  41. }
  42. describe('dateformat([now], [mask])', function() {
  43. _.each(dateFormat.masks, function(value, key) {
  44. it('should format `' + key + '` mask', function(done) {
  45. var now = new Date(2014, 10, 26, 13, 19, 44);
  46. var tzOffset = timezoneOffset(now);
  47. var expected = expects[key].replace(/%TZ_PREFIX%/, 'GMT')
  48. .replace(/%TZ_OFFSET%/g, tzOffset)
  49. .replace(/GMT\+0000/g, 'UTC');
  50. if (key === 'isoUtcDateTime') {
  51. var offset = parseOffset(now);
  52. now.setHours(now.getHours() - offset.hours,
  53. now.getMinutes() - offset.minutes);
  54. var expected = now.toISOString().replace(/\.000/g, '');
  55. }
  56. var actual = dateFormat(now, key);
  57. assert.strictEqual(actual, expected);
  58. done();
  59. });
  60. });
  61. it('should use `default` mask, when `mask` is empty', function(done) {
  62. var now = new Date(2014, 10, 26, 13, 19, 44);
  63. var expected = expects['default'];
  64. var actual = dateFormat(now);
  65. assert.strictEqual(actual, expected);
  66. done();
  67. });
  68. });