All files / datetime / day_of_year.ts

100.00% Branches 0/0
100.00% Lines 14/14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
 
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
 
 
 
x72
 
x72
x72
x72
 
x72
x72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
 
 
 
x71
 
x71
x71
 
x71
x71























































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

import { DAY } from "./constants.ts";

/**
 * Returns the number of the day in the year in the local time zone.
 *
 * @param date Date to get the day of the year of.
 * @return Number of the day in the year in the local time zone.
 *
 * @example Basic usage
 * ```ts
 * import { dayOfYear } from "@std/datetime/day-of-year";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(dayOfYear(new Date("2019-03-11T03:24:00")), 70);
 * ```
 */
export function dayOfYear(date: Date): number {
  // Values from 0 to 99 map to the years 1900 to 1999. All other values are the actual year. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)
  // Using setFullYear as a workaround

  const yearStart = new Date(date);

  yearStart.setFullYear(date.getFullYear(), 0, 0);
  const diff = (date.getTime() - date.getTimezoneOffset() * 60 * 1000) -
    (yearStart.getTime() - yearStart.getTimezoneOffset() * 60 * 1000);

  return Math.floor(diff / DAY);
}

/**
 * Returns the number of the day in the year in UTC time.
 *
 * @param date Date to get the day of the year of.
 * @return Number of the day in the year in UTC time.
 *
 * @example Usage
 * ```ts
 * import { dayOfYearUtc } from "@std/datetime/day-of-year";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(dayOfYearUtc(new Date("2019-03-11T03:24:00.000Z")), 70);
 * ```
 */
export function dayOfYearUtc(date: Date): number {
  // Values from 0 to 99 map to the years 1900 to 1999. All other values are the actual year. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)
  // Using setUTCFullYear as a workaround

  const yearStart = new Date(date);

  yearStart.setUTCFullYear(date.getUTCFullYear(), 0, 0);
  const diff = date.getTime() - yearStart.getTime();

  return Math.floor(diff / DAY);
}