2017-02-13 122 views
0

我有一个时间类,它具有单独计算小时,分钟和秒的功能。我要将计算的时间(格式为1小时30分20秒)下面代码中的toReadableString()方法)转换为HH; MM:SS格式。我已经看到了一些例子,但这并不能解决我的问题。另外,我想通过添加两个不同的时间段来计算总时间段(例如,第1个时间段是20分钟45秒,第2个时间段是1小时30分钟15秒, 1小时51分钟)。任何帮助表示感谢。提前感谢。将小时,分钟和秒转换为HH:MM:SS格式

public int getMinutes() 
    { 
     long minutesTotal = (time/1000/60); 

     return (int)minutesTotal % 60; 
    } 


    public int getSeconds() 
    { 
     return (int)(time - (getHours() * 60 * 60 * 1000) - (getMinutes() * 60 * 1000))/1000; 
    } 

    public int getHours() 
    { 
     return (int)(time/1000/60/60); 
    } 
    public String toString() 
    { 
     return "abs_" + Convert.ToString(time); 
    } 

    /** 
    * Convert time to a human readable string. 
    * @return - human readable string. 
    */ 
    public String toReadableString() 
    { 
     if (getHours() == 0 && getMinutes() == 0 && getSeconds() == 0) 
     { 
      if (getTime() > 0) 
      { 
       return getTime() + "ms"; 
      } 
      else 
      { 
       return "zero"; 
      } 
     } 

     String result = ""; 
     if (getHours() != 0) 
     { 
      result += Convert.ToString(getHours()) + "h "; 
     } 
     else 
     { 
      if (getMinutes() == 0) 
      { 
       return Convert.ToString(getSeconds()) + "sec"; 
      } 
     } 
     result += Convert.ToString(getMinutes()) + "m "; 
     result += Convert.ToString(getSeconds()) + "s"; 
     return result; 
    } 
+0

的可能的复制[:毫米:转换日期时间为ISO格式YYYY-MM-DD HH SS在C#(http://stackoverflow.com/questions/1912894/convert-datetime-to-iso-format -yyyy-mm-dd -hhmmss -in -c-sharp) – chadnt

+1

什么是数据类型的时间,int? – jjj

+0

[给定DateTime对象,如何获得字符串格式的ISO 8601日期?](http://stackoverflow.com/questions/114983/given-a-datetime-object-how-doi-i- get-an-iso-8601-date-in-string-format) – jjj

回答

2

在C#中,您可以使用TimeSpan对这些时间值进行数学运算。

试试这个:

var first = new TimeSpan(0, 20, 45); // 20mins 45secs 
var second = new TimeSpan(1, 30, 15); // 2nd time slot is 1hr30mins15secs 
var result = first + second; 

Debug.WriteLine(result.ToString()); 

public String toReadableString(TimeSpan ts) 
{ 
    // TODO: Write your function that receives a TimeSpan and generates the desired output string formatted... 
    return ts.ToString(); // 01:51:00 
} 
+1

感谢Toni.It工作! – user7274707

相关问题