index.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import moment, { DurationInputArg1, Moment, unitOfTime } from 'moment'
  2. /**
  3. * 获取两个时间范围内的所有时间
  4. * @param t1 时间1
  5. * @param t2 时间2
  6. * @param format 时间格式化类型
  7. * @param unit 时间单位
  8. * @param amount 时间区间间隔数
  9. * @returns
  10. */
  11. export function getRangeTime(t1: string | Moment | Date, t2: string | Moment | Date, format = 'YYYYMMDD', unit: unitOfTime.DurationConstructor = 'd', amount: DurationInputArg1 = 1): string[] {
  12. const fn = (val: Moment) => val.format(format);
  13. // 处理开始时间和结束时间
  14. let startTime = moment(t1);
  15. let endTime = moment(t2);
  16. const result: string[] = [];
  17. const isSame = () => startTime.isSame(endTime, unit);
  18. if (isSame()) {
  19. return [fn(startTime), fn(startTime)];
  20. } else {
  21. if (startTime.isAfter(endTime)) {
  22. [startTime, endTime] = [endTime, startTime]
  23. }
  24. while (!isSame()) {
  25. result.push(fn(startTime));
  26. startTime = startTime.add(amount, unit);
  27. }
  28. result.push(fn(endTime));
  29. return result;
  30. }
  31. }