dateTime.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import {Component} from 'react';
  2. import moment from 'moment';
  3. import momentTimezone from 'moment-timezone';
  4. import ConfigStore from 'app/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. return 'MMM DD, LT';
  33. }
  34. // 4:57 PM
  35. if (timeOnly) {
  36. if (clock24Hours) {
  37. return 'HH:mm';
  38. }
  39. return 'LT';
  40. }
  41. if (shortDate) {
  42. return 'MM/DD/YYYY';
  43. }
  44. // Oct 26, 2017 11:30
  45. if (clock24Hours) {
  46. return 'MMM D, YYYY HH:mm';
  47. }
  48. // Oct 26, 2017 11:30:30 AM
  49. if (seconds) {
  50. return 'll LTS z';
  51. }
  52. // Default is Oct 26, 2017 11:30 AM
  53. return 'lll';
  54. };
  55. render() {
  56. const {
  57. date,
  58. utc,
  59. seconds: _seconds,
  60. shortDate: _shortDate,
  61. dateOnly: _dateOnly,
  62. timeOnly: _timeOnly,
  63. timeAndDate: _timeAndDate,
  64. ...carriedProps
  65. } = this.props;
  66. const user = ConfigStore.get('user');
  67. const options = user?.options;
  68. const format = this.getFormat(options);
  69. return (
  70. <time {...carriedProps}>
  71. {utc
  72. ? moment.utc(date as moment.MomentInput).format(format)
  73. : momentTimezone.tz(date, options?.timezone ?? '').format(format)}
  74. </time>
  75. );
  76. }
  77. }
  78. export default DateTime;