dayOfYear method
Calculates the day of the year for the current DateTime
object.
This method returns an integer representing the day of the year, where:
- January 1st returns
1
- December 31st returns
365
(or366
in a leap year)
Example Usage:
final date = DateTime(2025, 2, 5);
print(date.dayOfYear()); // Output: 36 (since February 5th is the 36th day in 2025)
Leap Year Example:
final leapYearDate = DateTime(2024, 12, 31);
print(leapYearDate.dayOfYear()); // Output: 366 (2024 is a leap year)
Use Cases:
- Determining the day of the year for seasonal calculations.
- Useful for generating Julian dates or for analytics based on yearly progress.
Performance:
- Time complexity: O(1)
- Space complexity: O(1)
Implementation
int dayOfYear() {
final startOfYear = DateTime(year, 1, 1);
return difference(startOfYear).inDays + 1;
}