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.
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.
DateTime now = DateTime.Now;
DateTime end = new DateTime(now.Year + 1, 1, 1);
int daysLeftInYear = (int)(end - now).TotalDays;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With