dateTime.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import moment from 'moment';
  2. import momentTimezone from 'moment-timezone';
  3. import ConfigStore from 'sentry/stores/configStore';
  4. import {getFormat} from 'sentry/utils/dates';
  5. interface Props extends React.HTMLAttributes<HTMLTimeElement> {
  6. /**
  7. * Input date.
  8. */
  9. date: moment.MomentInput | momentTimezone.MomentInput;
  10. /**
  11. * If true, will only return the date part, e.g. "Jan 1".
  12. */
  13. dateOnly?: boolean;
  14. /**
  15. * When set, will force the date time display to be in the specified timezone
  16. */
  17. forcedTimezone?: string;
  18. /**
  19. * Formatting string. If specified, this formatting string will override all
  20. * other formatting props (dateOnly, timeOnly, year).
  21. */
  22. format?: string;
  23. /**
  24. * Whether to show the seconds. Is false by default.
  25. */
  26. seconds?: boolean;
  27. /**
  28. * If true, will only return the time part, e.g. "2:50 PM"
  29. */
  30. timeOnly?: boolean;
  31. /**
  32. * Whether to show the time zone. If not specified, the returned date string
  33. * will not contain the time zone _unless_ the time is UTC, in which case
  34. * the user would want to know that it's UTC and not their own time zone.
  35. */
  36. timeZone?: boolean;
  37. /**
  38. * Whether the date input is UTC time or not.
  39. */
  40. utc?: boolean;
  41. /**
  42. * Whether to show the year. If not specified, the returned date string will
  43. * not contain the year _if_ the date is not in the current calendar year.
  44. * For example: "Feb 1" (2022), "Jan 1" (2022), "Dec 31, 2021".
  45. */
  46. year?: boolean;
  47. }
  48. function DateTime({
  49. format,
  50. date,
  51. utc,
  52. dateOnly,
  53. timeOnly,
  54. year,
  55. timeZone,
  56. seconds = false,
  57. forcedTimezone,
  58. ...props
  59. }: Props) {
  60. const user = ConfigStore.get('user');
  61. const options = user?.options;
  62. const formatString =
  63. format ??
  64. getFormat({
  65. dateOnly,
  66. timeOnly,
  67. // If the year prop is defined, then use it. Otherwise only show the year if `date`
  68. // is in the current year.
  69. year: year ?? moment().year() !== moment(date).year(),
  70. // If timeZone is defined, use it. Otherwise only show the time zone if we're using
  71. // UTC time.
  72. timeZone: timeZone ?? utc,
  73. seconds,
  74. ...options,
  75. });
  76. return (
  77. <time {...props}>
  78. {utc
  79. ? moment.utc(date as moment.MomentInput).format(formatString)
  80. : momentTimezone
  81. .tz(date, forcedTimezone ?? options?.timezone ?? '')
  82. .format(formatString)}
  83. </time>
  84. );
  85. }
  86. export default DateTime;