To get TimeSpan in minutes from given two Dates I am doing the following
int totalMinutes = 0;
TimeSpan outresult = end.Subtract(start);
totalMinutes = totalMinutes + ((end.Subtract(start).Days) * 24 * 60) + ((end.Subtract(start).Hours) * 60) +(end.Subtract(start).Minutes);
return totalMinutes;
Is there a better way?
TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;
Why not just doing it this way?
DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;
Hope this helps.
我会这样做:
int totalMinutes = (int)(end - start).TotalMinutes;
See TimeSpan.TotalMinutes :
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
double totalMinutes = (end-start).TotalMinutes;
From my point of view I think we can calculate it in this way without using TimeSpan which I describe below :
At first we need a function which will subtract our present time and uploaded time value of database time.
public int GetMinute(int presentMinute, int uploadedMinute) { int result = presentMinute - uploadedMinute; return result; }
Then we need to declare our value from, two different DateTime and then fetch out the value 'Minute' from that.
DateTime presentDateTime = DateTime.Now; // it is present time (supppose 2019-10-31 02:32:21 ) DateTime uploadedDateTime = databaseValue; // it is database time (suppose 2019-11-03 06:27:23 )
3.Then called the above function GetMinute .
int resultMinute = GetMinute(presentDateTime.Minute, uploadedDateTime.Minute); //only passed the minute
if (resultMinute > 1)
{
return resultMinute + "m";
}
else if (resultMinute == 0 && presentDateTime.Hour != uploadedDateTime.Hour) //checking if the hour is not same.
{
return uploadedDateTime.Minute + "m";
}
else if (resultMinute < 1)
{
int calcuResult = Math.Abs(resultMinute); //here I change negative value to positive value
calcuResult = 60 - calcuResult;
return calcuResult + "m";
}
else
{
return "Just now";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.