MCPcopy Create free account
hub / github.com/codemix/graph / truncateDate

Function truncateDate

packages/graph/src/TemporalTypes.ts:1893–1950  ·  view source on GitHub ↗
(
  unit: TruncateUnit,
  date: DateValue,
  overrides?: Record<string, number>,
)

Source from the content-addressed store, hash-verified

1891 * Truncate a date to a specific unit
1892 */
1893export function truncateDate(
1894 unit: TruncateUnit,
1895 date: DateValue,
1896 overrides?: Record<string, number>,
1897): DateValue {
1898 let year = date.year;
1899 let month = 1;
1900 let day = 1;
1901
1902 switch (unit) {
1903 case "millennium":
1904 year = Math.floor((year - 1) / 1000) * 1000 + 1;
1905 break;
1906 case "century":
1907 year = Math.floor((year - 1) / 100) * 100 + 1;
1908 break;
1909 case "decade":
1910 year = Math.floor(year / 10) * 10;
1911 break;
1912 case "year":
1913 // Keep year, reset to Jan 1
1914 break;
1915 case "quarter":
1916 month = Math.floor((date.month - 1) / 3) * 3 + 1;
1917 break;
1918 case "month":
1919 month = date.month;
1920 break;
1921 case "week": {
1922 // Find Monday of the week (ISO week starts on Monday)
1923 const jsDate = new Date(Date.UTC(date.year, date.month - 1, date.day));
1924 const dayOfWeek = jsDate.getUTCDay() || 7; // Convert Sunday=0 to 7
1925 jsDate.setUTCDate(jsDate.getUTCDate() - (dayOfWeek - 1));
1926 return new DateValue(
1927 jsDate.getUTCFullYear(),
1928 jsDate.getUTCMonth() + 1,
1929 overrides?.day ?? jsDate.getUTCDate(),
1930 );
1931 }
1932 case "day":
1933 month = date.month;
1934 day = date.day;
1935 break;
1936 default:
1937 // For time-based units, just return the date as-is
1938 month = date.month;
1939 day = date.day;
1940 break;
1941 }
1942
1943 // Apply overrides
1944 if (overrides) {
1945 if (overrides.day !== undefined) day = overrides.day;
1946 if (overrides.month !== undefined) month = overrides.month;
1947 }
1948
1949 return new DateValue(year, month, day);
1950}

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected