dateTime.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import {Component} from 'react';
  2. import moment from 'moment';
  3. import momentTimezone from 'moment-timezone';
  4. import ConfigStore from 'sentry/stores/configStore';
  5. type DefaultProps = {
  6. seconds: boolean;
  7. };
  8. type Props = DefaultProps & {
  9. date: moment.MomentInput | momentTimezone.MomentInput;
  10. dateOnly?: boolean;
  11. timeOnly?: boolean;
  12. shortDate?: boolean;
  13. timeAndDate?: boolean;
  14. utc?: boolean;
  15. format?: string;
  16. };
  17. class DateTime extends Component<Props> {
  18. static defaultProps: DefaultProps = {
  19. seconds: true,
  20. };
  21. getFormat = ({clock24Hours}: {clock24Hours: boolean}): string => {
  22. const {dateOnly, timeOnly, seconds, shortDate, timeAndDate, format} = this.props;
  23. if (format) {
  24. return format;
  25. }
  26. // October 26, 2017
  27. if (dateOnly) {
  28. return 'LL';
  29. }
  30. // Oct 26, 11:30 AM
  31. if (timeAndDate) {
  32. if (clock24Hours) {
  33. return 'MMM DD, HH:mm';
  34. }
  35. return 'MMM DD, LT';
  36. }
  37. // 4:57 PM
  38. if (timeOnly) {
  39. if (clock24Hours) {
  40. return 'HH:mm';
  41. }
  42. return 'LT';
  43. }
  44. if (shortDate) {
  45. return 'MM/DD/YYYY';
  46. }
  47. // Oct 26, 2017 11:30
  48. if (clock24Hours) {
  49. return 'MMM D, YYYY HH:mm';
  50. }
  51. // Oct 26, 2017 11:30:30 AM
  52. if (seconds) {
  53. return 'll LTS z';
  54. }
  55. // Default is Oct 26, 2017 11:30 AM
  56. return 'lll';
  57. };
  58. render() {
  59. const {
  60. date,
  61. utc,
  62. seconds: _seconds,
  63. shortDate: _shortDate,
  64. dateOnly: _dateOnly,
  65. timeOnly: _timeOnly,
  66. timeAndDate: _timeAndDate,
  67. ...carriedProps
  68. } = this.props;
  69. const user = ConfigStore.get('user');
  70. const options = user?.options;
  71. const format = this.getFormat(options);
  72. return (
  73. <time {...carriedProps}>
  74. {utc
  75. ? moment.utc(date as moment.MomentInput).format(format)
  76. : momentTimezone.tz(date, options?.timezone ?? '').format(format)}
  77. </time>
  78. );
  79. }
  80. }
  81. export default DateTime;