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.2KB

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