C# 如何从给定日期获取一年中的总天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10495802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:03:48  来源:igfitidea点击:

How to get the total number of days in a year from the given date

c#asp.net

提问by Vivekh

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..

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

采纳答案by yamen

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.TotalDayscontains the number of days (thanks @Tung). lastdatealso contains the last date for the year.

diff.TotalDays包含天数(感谢@Tung)。lastdate还包含该年的最后日期。

回答by Dejan Janju?evi?

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

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

回答by ry8806

should do the trick

应该做的伎俩

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

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

回答by Tanveer

I think you should try TimeSpan like

我认为你应该像 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 );