Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How many days left in year from Datetime.Now

Tags:

c#

datetime

I'm trying to get the number of days left in a year from Datetime.Now.

Having a little trouble, I tried using a datediff without much success.

I don't suppose one of you experts could perhaps show me how this would be achieved in C#?

I'd like a code to return an integer value for the days remaining.

like image 384
Michael Benson Avatar asked Dec 10 '22 06:12

Michael Benson


2 Answers

How about:

DateTime date = DateTime.Today;
int daysInYear = DateTime.IsLeapYear(date.Year) ? 366 : 365;
int daysLeftInYear = daysInYear - date.DayOfYear; // Result is in range 0-365.

Note that it's important to only evaluate DateTime.Now once, otherwise you could get an inconsistency if it evaluates once at the end of one year and once at the start of another.

like image 163
Jon Skeet Avatar answered Dec 11 '22 20:12

Jon Skeet


DateTime now = DateTime.Now;
DateTime end = new DateTime(now.Year + 1, 1, 1);
int daysLeftInYear = (int)(end - now).TotalDays;
like image 25
Tim Lloyd Avatar answered Dec 11 '22 21:12

Tim Lloyd