[英]How to get Difference hours Between two date
I want get diffrences Day , Hour and Day between two days. 我想在两天之间区分Day , Hour和Day 。
I use belowe Code : 我使用下面的代码:
DateTime LastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
int differenceDay = DateTime.Now.Subtract(LastDate).Days;
int differenceHoure = DateTime.Now.Hour - LastDate.Hour;//returns -11
int differenceMinute = DateTime.Now.Minute - LastDate.Minute;
When I want get Hours its return mines (-11 et). 当我想获得Hours时,它会返回我的地雷(-11 et)。
How can I get positive Diffrence Hour ? 我如何获得正时差?
anyone can you help me? 有人可以帮我吗? I want get Last Dat and show its by string how days afterd now. 我想要获取最后一个日期,并按字符串显示其现在的日期。
You're subtracting component-wise (ie "this hour-of-day minus that hour-of-day, this minute-of-hour minus that minute-of-hour"). 您正在按分量进行减法(即“该小时减去该小时,此分钟减去该小时”)。 Don't do that - it won't work if the current hour-of-day is earlier than the hour-of-day of lastDate
, or the same for minute-of-hour - you get a negative value, exactly as you've seen. 请勿这样做-如果当前时间早于lastDate
的小时,或者小时的分钟相同, lastDate
-您得到的负值与您'已经看到。
Instead, subtract one DateTime
from another to get a TimeSpan
and use that single TimeSpan
for all the components: 而是从另一个减去一个DateTime
以获得一个TimeSpan
,并对所有组件使用该单个TimeSpan
:
DateTime lastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
TimeSpan difference = DateTime.Now - lastDate;
int days = difference.Days;
int hours = difference.Hours;
int minutes = difference.Minutes;
That will still be negative if lastDate
is after DateTime.Now
, of course. 当然,如果lastDate
在DateTime.Now
之后,它将仍然为负。
Note that this will give you a result which is meaningful if you display all three components. 请注意,如果显示所有三个组件,这将为您带来有意义的结果。 For example, it might give you "2 days, 3 hours and 10 minutes". 例如,它可能会给您“ 2天3小时10分钟”。 If instead you want to represent the same TimeSpan
as "2.194 days" or "51.166 hours" or "3160 minutes" then you can use TotalDays
, TotalHours
and TotalMinutes
. 相反,如果您要表示与“ 2.194天”或“ 51.166小时”或“ 3160分钟”相同的TimeSpan
,则可以使用TotalDays
, TotalHours
和TotalMinutes
。
If you always want a positive TimeSpan
- the equivalent of Math.Abs
but for TimeSpan
you can just use TimeSpan.Duration()
: 如果您始终想要一个正的TimeSpan
与Math.Abs
等效,但是对于TimeSpan
您可以使用TimeSpan.Duration()
:
TimeSpan difference = (DateTime.Now - lastDate).Duration();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.