You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

time.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import dayjs from 'dayjs';
  2. import utc from 'dayjs/plugin/utc.js';
  3. import {getCurrentLocale} from '../utils.js';
  4. dayjs.extend(utc);
  5. /**
  6. * Returns an array of millisecond-timestamps of start-of-week days (Sundays)
  7. *
  8. * @param startConfig The start date. Can take any type that `Date` accepts.
  9. * @param endConfig The end date. Can take any type that `Date` accepts.
  10. */
  11. export function startDaysBetween(startDate, endDate) {
  12. const start = dayjs.utc(startDate);
  13. const end = dayjs.utc(endDate);
  14. let current = start;
  15. // Ensure the start date is a Sunday
  16. while (current.day() !== 0) {
  17. current = current.add(1, 'day');
  18. }
  19. const startDays = [];
  20. while (current.isBefore(end)) {
  21. startDays.push(current.valueOf());
  22. current = current.add(1, 'week');
  23. }
  24. return startDays;
  25. }
  26. export function firstStartDateAfterDate(inputDate) {
  27. if (!(inputDate instanceof Date)) {
  28. throw new Error('Invalid date');
  29. }
  30. const dayOfWeek = inputDate.getUTCDay();
  31. const daysUntilSunday = 7 - dayOfWeek;
  32. const resultDate = new Date(inputDate.getTime());
  33. resultDate.setUTCDate(resultDate.getUTCDate() + daysUntilSunday);
  34. return resultDate.valueOf();
  35. }
  36. export function fillEmptyStartDaysWithZeroes(startDays, data) {
  37. const result = {};
  38. for (const startDay of startDays) {
  39. result[startDay] = data[startDay] || {'week': startDay, 'additions': 0, 'deletions': 0, 'commits': 0};
  40. }
  41. return Object.values(result);
  42. }
  43. let dateFormat;
  44. // format a Date object to document's locale, but with 24h format from user's current locale because this
  45. // option is a personal preference of the user, not something that the document's locale should dictate.
  46. export function formatDatetime(date) {
  47. if (!dateFormat) {
  48. // TODO: replace `hour12` with `Intl.Locale.prototype.getHourCycles` once there is broad browser support
  49. dateFormat = new Intl.DateTimeFormat(getCurrentLocale(), {
  50. day: 'numeric',
  51. month: 'short',
  52. year: 'numeric',
  53. hour: 'numeric',
  54. hour12: !Number.isInteger(Number(new Intl.DateTimeFormat([], {hour: 'numeric'}).format())),
  55. minute: '2-digit',
  56. timeZoneName: 'short',
  57. });
  58. }
  59. return dateFormat.format(date);
  60. }