两个日期之间经过的时间

时间:2014-07-02 16:33:04

标签: c# c#-4.0 datetime if-statement time

我想找到两个日期之间经过的确切时间,条件是如果任何值为“0”,其测量单位应该消失。例如,如果小时和分钟是o,则经过的时间应该是1天40秒而不是1天0小时0分40秒。

TimeSpan elapsed = completdDate.Subtract(insertdDate);

int daysEl= elapsed.Days;
int hrsEl= elapsed.Hours;
int minsEl = elapsed.Minutes;
int secEl = elapsed.Seconds;

string totalTime = string.Empty;
string days = string.Empty;
string hours = string.Empty;
string mins = string.Empty;
string secs = string.Empty;

if (daysEl == 0 )
    days = days.Replace(daysEl.ToString() , "");
else
  days = daysEl.ToString();

if (hrsEl==0)
    hours = hours.Replace(hrsEl.ToString() , "");
else 
    hours = hrsEl.ToString();

if (minsEl == 0)
    mins = mins.Replace(minsEl.ToString(), "");
else
    mins = minsEl.ToString();

if (secEl == 0)
    secs = secs.Replace(secEl.ToString(), "");
else 
    secs = secEl.ToString();

totalTime = days  + "days" 
          + hours + "hours" 
          + mins  + "minutes" 
          + secs  + "seconds";

*********输出************** ***************

Output Image If any value is zero its unit should disappear

3 个答案:

答案 0 :(得分:2)

您可以删除中间字符串和if语句:

totalTime = 
    (daysEl  == 0 ? "" : (daysEl  + " days "))
  + (hoursEl == 0 ? "" : (hoursEl + " hours "))
  + (minsEl  == 0 ? "" : (minsEl  + " minutes "))
  + (secsEl  == 0 ? "" : (secsEl  + " seconds "));

答案 1 :(得分:1)

如果您想省略零值,您更有可能查看格式问题,而不是计算问题,并且使用StringBuilder可能更容易。

var sb = new StringBuilder();

if (elapsed.Days != 0)
    sb.AppendFormat("{0} days ", elapsed.Days);
if (elapsed.Hours != 0)
    sb.AppendFormat("{0} hours ", elapsed.Hours);
if (elapsed.Minutes != 0)
    sb.AppendFormat("{0} minutes ", elapsed.Minutes);
if (elapsed.Seconds != 0)
    sb.AppendFormat("{0} seconds ", elapsed.Seconds);

if (sb.Length == 0)
    return "instant!";

// get rid of the last space in there!
return sb.ToString().Substring(0,sb.Length-1); 

通过使用格式,您可以更简洁地将值与单位绑定(即" 14秒"),从而将整个部分放入if语句,完全绕过该部分如果它为零。

答案 2 :(得分:0)

void Main()
{
    TimeSpan elapsed = DateTime.Now - DateTime.Now.AddDays(-1);

    int daysEl= elapsed.Days;
    int hrsEl= elapsed.Hours;
    int minsEl = elapsed.Minutes;
    int secEl = elapsed.Seconds;

    var sb = new StringBuilder();

    if (daysEl != 0 )
        sb.Append(daysEl + " days ");
    if (hrsEl != 0)
        sb.Append(hrsEl + " hours ");
    if (minsEl != 0)
        sb.Append(minsEl + " mins ");   
    if (secEl != 0)
        sb.Append(secEl + " secs ");

    string totalTime = sb.ToString();

    Console.WriteLine (totalTime);
}