如何将秒转换为(小时:分钟:秒:毫秒)时间?
假设我有80秒;. net中有没有专门的类/技术可以让我把这80秒转换成(00h:00m:00s:00ms)格式,比如convert。ToDateTime之类的?
如何将秒转换为(小时:分钟:秒:毫秒)时间?
假设我有80秒;. net中有没有专门的类/技术可以让我把这80秒转换成(00h:00m:00s:00ms)格式,比如convert。ToDateTime之类的?
当前回答
得到总秒数
var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;
并从秒获取datetime
var thatDateTime = new DateTime().AddSeconds(i)
其他回答
如果我们有DateTime. addseconds(),为什么人们需要TimeSpan和DateTime ?
var dt = new DateTime(2015, 1, 1).AddSeconds(totalSeconds);
日期是任意的。 totalSeconds可以大于59,它是一个double。 然后你可以使用DateTime.ToString()格式化你的时间:
dt.ToString("H:mm:ss");
如果totalSeconds < 0或> 59:
new DateTime(2015, 1, 1, 0, 0, totalSeconds)
private string ConvertTime(double miliSeconds)
{
var timeSpan = TimeSpan.FromMilliseconds(totalMiliSeconds);
// Converts the total miliseconds to the human readable time format
return timeSpan.ToString(@"hh\:mm\:ss\:fff");
}
/ /测试
[TestCase(1002, "00:00:01:002")]
[TestCase(700011, "00:11:40:011")]
[TestCase(113879834, "07:37:59:834")]
public void ConvertTime_ResturnsCorrectString(double totalMiliSeconds, string expectedMessage)
{
// Arrange
var obj = new Class();;
// Act
var resultMessage = obj.ConvertTime(totalMiliSeconds);
// Assert
Assert.AreEqual(expectedMessage, resultMessage);
}
在VB。NET,但是在c#中也是一样的:
Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
TimeSpan构造函数允许以秒为单位传递。只需声明一个TimeSpan类型的变量(秒数)。例:
TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
TimeSpan t = TimeSpan.FromSeconds(EnergyRestoreTimer.Instance.SecondsForRestore);
string sTime = EnergyRestoreTimer.Instance.SecondsForRestore < 3600
? $"{t.Hours:D2}:{t.Minutes:D2}:{t.Seconds:D2}"
: $"{t.Minutes:D2}:{t.Seconds:D2}";
time.text = sTime;