dateTime.tsx 1.8 KB

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