dateTime.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. format?: string;
  12. shortDate?: boolean;
  13. timeAndDate?: boolean;
  14. timeOnly?: boolean;
  15. utc?: boolean;
  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. if (clock24Hours) {
  48. if (seconds) {
  49. // Oct 26, 2017 11:30:30
  50. return 'MMM D, YYYY HH:mm:ss';
  51. }
  52. // Oct 26, 2017 11:30
  53. return 'MMM D, YYYY HH:mm';
  54. }
  55. // Oct 26, 2017 11:30:30 AM
  56. if (seconds) {
  57. return 'll LTS z';
  58. }
  59. // Default is Oct 26, 2017 11:30 AM
  60. return 'lll';
  61. };
  62. render() {
  63. const {
  64. date,
  65. utc,
  66. seconds: _seconds,
  67. shortDate: _shortDate,
  68. dateOnly: _dateOnly,
  69. timeOnly: _timeOnly,
  70. timeAndDate: _timeAndDate,
  71. ...carriedProps
  72. } = this.props;
  73. const user = ConfigStore.get('user');
  74. const options = user?.options;
  75. const format = this.getFormat(options);
  76. return (
  77. <time {...carriedProps}>
  78. {utc
  79. ? moment.utc(date as moment.MomentInput).format(format)
  80. : momentTimezone.tz(date, options?.timezone ?? '').format(format)}
  81. </time>
  82. );
  83. }
  84. }
  85. export default DateTime;