index.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import toDate from "../toDate/index.js";
  2. import formatters from "../_lib/format/lightFormatters/index.js";
  3. import getTimezoneOffsetInMilliseconds from "../_lib/getTimezoneOffsetInMilliseconds/index.js";
  4. import isValid from "../isValid/index.js";
  5. import subMilliseconds from "../subMilliseconds/index.js";
  6. import requiredArgs from "../_lib/requiredArgs/index.js"; // This RegExp consists of three parts separated by `|`:
  7. // - (\w)\1* matches any sequences of the same letter
  8. // - '' matches two quote characters in a row
  9. // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
  10. // except a single quote symbol, which ends the sequence.
  11. // Two quote characters do not end the sequence.
  12. // If there is no matching single quote
  13. // then the sequence will continue until the end of the string.
  14. // - . matches any single character unmatched by previous parts of the RegExps
  15. var formattingTokensRegExp = /(\w)\1*|''|'(''|[^'])+('|$)|./g;
  16. var escapedStringRegExp = /^'([^]*?)'?$/;
  17. var doubleQuoteRegExp = /''/g;
  18. var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
  19. /**
  20. * @name lightFormat
  21. * @category Common Helpers
  22. * @summary Format the date.
  23. *
  24. * @description
  25. * Return the formatted date string in the given format. Unlike `format`,
  26. * `lightFormat` doesn't use locales and outputs date using the most popular tokens.
  27. *
  28. * > ⚠️ Please note that the `lightFormat` tokens differ from Moment.js and other libraries.
  29. * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
  30. *
  31. * The characters wrapped between two single quotes characters (') are escaped.
  32. * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
  33. *
  34. * Format of the string is based on Unicode Technical Standard #35:
  35. * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
  36. *
  37. * Accepted patterns:
  38. * | Unit | Pattern | Result examples |
  39. * |---------------------------------|---------|-----------------------------------|
  40. * | AM, PM | a..aaa | AM, PM |
  41. * | | aaaa | a.m., p.m. |
  42. * | | aaaaa | a, p |
  43. * | Calendar year | y | 44, 1, 1900, 2017 |
  44. * | | yy | 44, 01, 00, 17 |
  45. * | | yyy | 044, 001, 000, 017 |
  46. * | | yyyy | 0044, 0001, 1900, 2017 |
  47. * | Month (formatting) | M | 1, 2, ..., 12 |
  48. * | | MM | 01, 02, ..., 12 |
  49. * | Day of month | d | 1, 2, ..., 31 |
  50. * | | dd | 01, 02, ..., 31 |
  51. * | Hour [1-12] | h | 1, 2, ..., 11, 12 |
  52. * | | hh | 01, 02, ..., 11, 12 |
  53. * | Hour [0-23] | H | 0, 1, 2, ..., 23 |
  54. * | | HH | 00, 01, 02, ..., 23 |
  55. * | Minute | m | 0, 1, ..., 59 |
  56. * | | mm | 00, 01, ..., 59 |
  57. * | Second | s | 0, 1, ..., 59 |
  58. * | | ss | 00, 01, ..., 59 |
  59. * | Fraction of second | S | 0, 1, ..., 9 |
  60. * | | SS | 00, 01, ..., 99 |
  61. * | | SSS | 000, 001, ..., 999 |
  62. * | | SSSS | ... |
  63. *
  64. * @param {Date|Number} date - the original date
  65. * @param {String} format - the string of tokens
  66. * @returns {String} the formatted date string
  67. * @throws {TypeError} 2 arguments required
  68. * @throws {RangeError} format string contains an unescaped latin alphabet character
  69. *
  70. * @example
  71. * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd')
  72. * //=> '2014-02-11'
  73. */
  74. export default function lightFormat(dirtyDate, formatStr) {
  75. requiredArgs(2, arguments);
  76. var originalDate = toDate(dirtyDate);
  77. if (!isValid(originalDate)) {
  78. throw new RangeError('Invalid time value');
  79. }
  80. // Convert the date in system timezone to the same date in UTC+00:00 timezone.
  81. // This ensures that when UTC functions will be implemented, locales will be compatible with them.
  82. // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
  83. var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
  84. var utcDate = subMilliseconds(originalDate, timezoneOffset);
  85. var tokens = formatStr.match(formattingTokensRegExp);
  86. // The only case when formattingTokensRegExp doesn't match the string is when it's empty
  87. if (!tokens) return '';
  88. var result = tokens.map(function (substring) {
  89. // Replace two single quote characters with one single quote character
  90. if (substring === "''") {
  91. return "'";
  92. }
  93. var firstCharacter = substring[0];
  94. if (firstCharacter === "'") {
  95. return cleanEscapedString(substring);
  96. }
  97. var formatter = formatters[firstCharacter];
  98. if (formatter) {
  99. return formatter(utcDate, substring);
  100. }
  101. if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
  102. throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
  103. }
  104. return substring;
  105. }).join('');
  106. return result;
  107. }
  108. function cleanEscapedString(input) {
  109. var matches = input.match(escapedStringRegExp);
  110. if (!matches) {
  111. return input;
  112. }
  113. return matches[1].replace(doubleQuoteRegExp, "'");
  114. }