58745592d59cdbd3cccccacc758f9d91eb5f5182448ab1a4344b129a736a6437ed58c960c4aa6a63420a034f55794acdc0a7f4bd389ca3e5b1c299fe556a24 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { createLocal } from '../create/local';
  2. import { cloneWithOffset } from '../units/offset';
  3. import isFunction from '../utils/is-function';
  4. import { hooks } from '../utils/hooks';
  5. import { isMomentInput } from '../utils/is-moment-input';
  6. import isCalendarSpec from '../utils/is-calendar-spec';
  7. export function getCalendarFormat(myMoment, now) {
  8. var diff = myMoment.diff(now, 'days', true);
  9. return diff < -6
  10. ? 'sameElse'
  11. : diff < -1
  12. ? 'lastWeek'
  13. : diff < 0
  14. ? 'lastDay'
  15. : diff < 1
  16. ? 'sameDay'
  17. : diff < 2
  18. ? 'nextDay'
  19. : diff < 7
  20. ? 'nextWeek'
  21. : 'sameElse';
  22. }
  23. export function calendar(time, formats) {
  24. // Support for single parameter, formats only overload to the calendar function
  25. if (arguments.length === 1) {
  26. if (!arguments[0]) {
  27. time = undefined;
  28. formats = undefined;
  29. } else if (isMomentInput(arguments[0])) {
  30. time = arguments[0];
  31. formats = undefined;
  32. } else if (isCalendarSpec(arguments[0])) {
  33. formats = arguments[0];
  34. time = undefined;
  35. }
  36. }
  37. // We want to compare the start of today, vs this.
  38. // Getting start-of-today depends on whether we're local/utc/offset or not.
  39. var now = time || createLocal(),
  40. sod = cloneWithOffset(now, this).startOf('day'),
  41. format = hooks.calendarFormat(this, sod) || 'sameElse',
  42. output =
  43. formats &&
  44. (isFunction(formats[format])
  45. ? formats[format].call(this, now)
  46. : formats[format]);
  47. return this.format(
  48. output || this.localeData().calendar(format, this, createLocal(now))
  49. );
  50. }