C# - 计算截止日期之后的天数[改进] [英] C# - calculate number of days away from a deadline [improved]
问题描述
我已经获得预约的日期和时间,我需要返回它(预约)未来的天数。答案必须在整天;例如,今晚11点,明天上午9点的预约将是1天(而不是10小时)。
我尝试过这个问题(请参阅下面的代码)。但是,我在所有内容下面都有一条红色的波浪线,说明'不能隐式地将类型'double'转换为'int'。存在显式转换(您是否错过了演员表?)'。
请记住,我一直在做其他研究来学习C#,懒惰不是我通过发布我试过的问题。
感谢您的帮助。
问候。
我尝试过:
Hi,
I have been given the date and time of an appointment and I need to return how many days it (the appointment) is in the future. The answer must be in FULL days; for example, at 11 PM tonight, an appointment at 9 AM tomorrow would be 1 day (and not 10 hours).
I have attempted the question (please see the code below). However, I get a red squiggly line underneath everything, stating 'cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)'.
Please bear in mind that I am constantly doing other research to learn C#, and lazy is not what I am being by posting questions which I have attempted.
I appreciate your help.
Regards.
What I have tried:
public static int HowManyDaysFromToday(DateTime appointment)
{
return appointment.TimeOfDay.Subtract(DateTime.Now.TimeOfDay).TotalDays;
}
推荐答案
我建议剥离时间并比较两个日期:
Well I'd suggest stripping the time out and compare the two dates that way:
public static int HowManyDaysFromToday(DateTime appointment)
{
var today = DateTime.Today; //like DateTime.Now but with no time aspect
var appDay = appointment.Date;
return appDay.Subtract(today).TotalDays;
}
如果你想要那么你也可以用实际时间返回一个时间跨度:
If you wanted then you could return a timespan with the actual time too:
public static TimeSpan HowManyDaysFromToday(DateTime appointment)
{
var today = DateTime.Today; //like DateTime.Now but with no time aspect
var appDay = appointment.Date;
return appDay.Subtract(today) + appointment.Subtract(appDay); // or whatever
}
这样你就拥有了一个标准对象中的所有数据:
That way you have all the data in one standard object:
public override string ToString(){
var ts = HowManyDaysFromToday(_app);
return string.Format("{0} days at {1}:{2}",(int)ts.TotalDays,ts.Hours,ts.Minutes);
}
这不是一个好方法,但这只是一个想法^ _ ^
That's not a great way to do it, but it's just an idea ^_^
这与 C# - 计算距离截止日期的小时数 [ ^ ]除了这次你正在看Days。鉴于您需要完整或部分天数,您只需要将小时数除以24,如果有余数则加1。简单的数学真的。
This is basically the same issue as C# - calculate number of hours away from a deadline[^] except that this time you are looking at Days. Given that you want full or partial days you just need to divide the hours by 24 and add 1 if there is a remainder. Simple maths really.
这篇关于C# - 计算截止日期之后的天数[改进]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!