index.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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://git.io/fxCyr
  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, 0001, ..., 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. } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
  80. // This ensures that when UTC functions will be implemented, locales will be compatible with them.
  81. // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
  82. var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
  83. var utcDate = subMilliseconds(originalDate, timezoneOffset);
  84. var tokens = formatStr.match(formattingTokensRegExp); // The only case when formattingTokensRegExp doesn't match the string is when it's empty
  85. if (!tokens) return '';
  86. var result = tokens.map(function (substring) {
  87. // Replace two single quote characters with one single quote character
  88. if (substring === "''") {
  89. return "'";
  90. }
  91. var firstCharacter = substring[0];
  92. if (firstCharacter === "'") {
  93. return cleanEscapedString(substring);
  94. }
  95. var formatter = formatters[firstCharacter];
  96. if (formatter) {
  97. return formatter(utcDate, substring);
  98. }
  99. if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
  100. throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
  101. }
  102. return substring;
  103. }).join('');
  104. return result;
  105. }
  106. function cleanEscapedString(input) {
  107. var matches = input.match(escapedStringRegExp);
  108. if (!matches) {
  109. return input;
  110. }
  111. return matches[1].replace(doubleQuoteRegExp, "'");
  112. }