如何获取给定日期一年内的总天数

时间:2012-05-08 09:15:55

标签: c# asp.net

我想获得给定日期之后一年内剩余的总天数。假设用户是否提供04-01-2011(MM-DD-YYYY)我想找到剩余的剩余天数。怎么做..

5 个答案:

答案 0 :(得分:21)

假设日期是今天:

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包含天数(感谢@Tung)。 lastdate还包含该年的最后日期。

答案 1 :(得分:3)

应该做的伎俩

int daysLeft = new DateTime(DateTime.Now.Year, 12, 31).DayOfYear - DateTime.Now.DayOfYear;

答案 2 :(得分:3)

也许只是:

DateTime.IsLeapYear(DateTime.Now.Year)吗? 366:365

对不起,读起来就像您只想要当年的天数...

答案 3 :(得分:1)

new DateTime(suppliedDate.Year, 12, 31).Subtract(suppliedDate).TotalDays

答案 4 :(得分:0)

我认为你应该尝试像TimeSpan一样

 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 );