Amanda R. Amanda R. - 1 month ago 8
C# Question

How to get the number of days in a year from a given date


I need to calculate the day in a year from a given date, considering
the year too.

I'm in Brazil, so I'm using in the dd/mm/yyyy format

Console.WriteLine("Please inform the date in format dd/mm/yyyy");
DateTime dateInformed = DateTime.Parse(Console.ReadLine());
.
.
.
Console.WriteLine("The day of the year is:" + );


Examples:

If I receive: 21/10/2016 I show the number of days in 2016

If I receive: 21/10/1993 I show the number of days in 1993

Considering if it's leap year or not.

Sorry if I didn't explained well.

Thanks!


EDIT:
Some people reported as duplicate question, but I don't think so.

Let me try to explain in another way...

I'm going to receive the complete date from the user in Console.
I didn't figure out how to get the number of days in the year that the user gave to me in the format dd/mm/yyyy.
I think the calc is basically: date that the user entered - first day of the year. But I also need to know if this year is leap year or not.
But i don't know how to do this using DateTime in C#.

Another example...

25/10/2016 - 01/01/2016 = day 298 of the year

25/10/2015 - 01/01/2015 = day 297 of the year

I just have an idea receiving the day, month and year in different entrances.

Thank you!

Answer

Create a new DateTime object set at the last day of the year (31. December) and use the DayOfYear property.

int daysInYear=new DateTime(dateInformed.Year,12,31).DayOfYear;

Or check if it's a leap year using the IsLeapYear method:

int daysInYear=dateInformed.IsLeapYear()?366:365;