I would like to get the total number of days in a year left from the given date .. Assume if a user gives 04-01-2011(MM-DD-YYYY) I would like to find the remaining days left. How to do this..
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Let’s say the date is today:
var user = "05-08-2012"; var date = DateTime.ParseExact(user, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture); var lastdate = new DateTime(date.Year, 12, 31); var diff = lastdate - date;
diff.TotalDays contains the number of days (thanks @Tung). lastdate also contains the last date for the year.
Method 2
Perhaps just:
DateTime.IsLeapYear(DateTime.Now.Year) ? 366 : 365
Sorry, read it as if you just wanted the number of days in current year…
Method 3
should do the trick
int daysLeft = new DateTime(DateTime.Now.Year, 12, 31).DayOfYear - DateTime.Now.DayOfYear;
Method 4
new DateTime(suppliedDate.Year, 12, 31).Subtract(suppliedDate).TotalDays
Method 5
I think you should try TimeSpan like
DateTime startTime = DateTime.Now; DateTime endTime = DateTime.Now.AddSeconds( 75 ); TimeSpan span = endTime.Subtract ( startTime ); Console.WriteLine( "Time Difference (seconds): " + span.Seconds ); Console.WriteLine( "Time Difference (minutes): " + span.Minutes ); Console.WriteLine( "Time Difference (hours): " + span.Hours ); Console.WriteLine( "Time Difference (days): " + span.Days );
Method 6
Take some start date, add one year minus one day and then subtract the end date from the start date and you’ll get the total number of days between the two dates.
var beginOfYear = new DateTime(2000, 01, 01, 0, 0, 0, DateTimeKind.Local); var endOfYear = beginOfYear.AddYears(1).AddDays(-1); var daysOfYear = endOfYear.Subtract(beginOfYear).TotalDays;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0