9

我想获得从给定日期起一年中剩下的总天数。假设如果用户给出04-01-2011(MM-DD-YYYY)我想找到剩余的天数。这个怎么做..

4

6 回答 6

25

假设日期是今天:

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还包含该年的最后日期。

于 2012-05-08T09:19:18.557 回答
9

也许只是:

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

对不起,读起来好像你只是想要当年的天数......

于 2020-07-29T11:00:06.750 回答
4

应该做的伎俩

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

于 2012-05-08T09:21:31.537 回答
1

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

于 2012-05-08T09:20:15.157 回答
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 );
于 2012-05-08T09:46:36.420 回答
0

取一些开始日期,加上一年减去一天,然后从开始日期中减去结束日期,您将得到两个日期之间的总天数。

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;
于 2022-02-26T13:46:51.727 回答