chronia
    Preparing search index...

    Function setYear

    • Set the year of the given date.

      This function validates arguments before processing and returns a new Date instance with the specified year set. Fractional years are truncated toward zero.

      Parameters

      • date: number | Date

        The base date as a Date object or timestamp (number)

      • year: number

        The year to set (can be negative for BC dates)

      Returns Date

      A new Date object with the year set, or Invalid Date if any input is invalid

      // Set year to future year
      const result = setYear(new Date(2025, 0, 15), 2030);
      // Returns: 2030-01-15

      // Set year to past year
      const result2 = setYear(new Date(2025, 0, 15), 2020);
      // Returns: 2020-01-15

      // Leap year adjustment (Feb 29 → Feb 28)
      const result3 = setYear(new Date(2020, 1, 29), 2021);
      // Returns: 2021-02-28 (non-leap year)

      // Fractional year is truncated
      const result4 = setYear(new Date(2025, 0, 15), 2023.9);
      // Returns: 2023-01-15

      // Invalid date returns Invalid Date
      const result5 = setYear(new Date("invalid"), 2025);
      // Returns: Invalid Date
      • Validates arguments before conversion (consistent with library patterns)
      • Accepts both Date objects and numeric timestamps
      • Fractions are truncated using Math.trunc (2023.9 → 2023, -2023.9 → -2023)
      • Returns Invalid Date for: Invalid Date, NaN, Infinity, -Infinity
      • Preserves month, day, and time components (hours, minutes, seconds, milliseconds)
      • Special handling: When the source date is Feb 29 and the target year is not a leap year, the result becomes Feb 28
      • Always returns a new Date instance (does not mutate input)