I am trying to get the number of days left in a year from Datetime.Now .
Datetime.Now
Having a little problem, I tried using datediff without much success.
datediff
I donโt think one of your experts could show me how this will be achieved in C #?
I want the code to return an integer value for the remaining days.
What about:
DateTime date = DateTime.Today; int daysInYear = DateTime.IsLeapYear(date.Year) ? 366 : 365; int daysLeftInYear = daysInYear - date.DayOfYear; // Result is in range 0-365.
Please note that it is important to evaluate only DateTime.Now once, otherwise you may get inconsistency if it is evaluated once at the end of one year and once at the beginning of another.
DateTime.Now
DateTime now = DateTime.Now; DateTime end = new DateTime(now.Year + 1, 1, 1); int daysLeftInYear = (int)(end - now).TotalDays;
On top of my head you can do this:
Date someDate = DateTime.Now; Date nextYear = new DateTime(someDate.Year + 1, 1, 1); int daysLeft = (nextYear - someDate).Days;
Not tested because I'm at home, but I'm pretty sure of the logic. :)
How about this:
public int DaysLeftInYear() { DateTime today = DateTime.Now; int daysInYear = 365; if (DateTime.IsLeapYear(today.Year)) { daysInYear++; } return daysInYear - today.DayOfYear; }
something like that...
DateTime EOY = new DateTime(DateTime.Now.Year, 12, 31); int DaysLeft = EOY.Subtract(DateTime.Now).Days;
Already there are many answers that work, but have not seen this simple yet
DateTime today = DateTime.Now; int daysleft = new DateTime(today.Year,12,31).DayOfYear - today.DayOfYear;