我有一定的时间即。上午10:30用户在表格中输入。如果用户在上午10:30之后进入,则应计算从上午10点30分到当前时间的分钟数并将其设置为字符串。
这是我现在努力的目标: -
int hour = DateTime.Now.Hour;
int mins = DateTIme.Now.Minute
if(hour>10 && mins >30)
{
string lateBy = "You are late by:"+ //????? how do I calculate this?
}
任何帮助都会很棒
答案 0 :(得分:1)
使用TimeSpan
查找2个日期时间值之间的差异,并使用TotalMinutes
属性获取分钟数的差异。
DateTime today = DateTime.Today;
DateTime start = new DateTime(today.Year,today.Month,today.Day,10,30,00);
DateTime now = DateTime.Now;
int hour = now.Hour;
int mins = now.Minute;
TimeSpan ts = now.Subtract(start);
if(ts.TotalMinutes > 0) //Time now is after 10:30
{
string lateBy = "You are late by:"+ ts.TotalMinutes.ToString();
}
答案 1 :(得分:0)
忽略日期并假设它始终与10:30截止日期相同:
string lateBy = "You are late by:"+ ((hour-10)*60 + mins-30) + " minutes";
请注意,这仅适用于午夜之前,即同一天。
答案 2 :(得分:0)
由于两者都是DateTime,因此您可以使用DateTime.Subract
DateTime a = new DateTime(2014, 06, 20, 10, 30, 00);
DateTime b = DateTime.Now;
Console.WriteLine("You are late by:"+b.Subtract(a).TotalMinutes +"minutes");
Console.ReadLine();