twoDigitToFullYear.js 1.0 KB

123456789101112131415161718192021222324252627
  1. /**
  2. * Convert 2-digit year to 4-digit year
  3. * By default, 2-digit year will be converted to a year in the 100-year
  4. * period ending 50 years after the current year. The target 100-year period
  5. * can be changed by specifying base date and the length of the future side.
  6. * @param {Number} year - 2-digit year
  7. * @param {Number} [futureSideSpan] - number of yeas in the future side of
  8. * the target 100-year period. Default: 50
  9. * @param {Date} [baseDate] - base date to caliculate the target 100-year
  10. * period. if omitted, the current date is used.
  11. * @return {Number} 4-digit year
  12. */
  13. export function twoDigitToFullYear(year, futureSideSpan = 50, baseDate = undefined) {
  14. if (isNaN(year) || year > 99 || year < 0) {
  15. return year;
  16. }
  17. const date = baseDate instanceof Date && !isNaN(baseDate) ? baseDate : new Date();
  18. const currentYear = date.getFullYear();
  19. const endOfCurrent = currentYear + futureSideSpan;
  20. let century = Math.floor(endOfCurrent / 100) * 100;
  21. if (year > endOfCurrent % 100) {
  22. century -= 100;
  23. }
  24. return year + century;
  25. }