What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?
将秒转换为(小时:分钟:秒:毫秒)时间的最佳方法是什么?
Let's say I have 80 seconds, are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like to DateTime or something?
假设我有80秒,.NET中是否有任何专门的类/技术可以将这些80秒转换为(00h:00m:00s:00ms)格式,比如DateTime或其他东西?
12 个解决方案
#1
For .Net <= 4.0 Use the TimeSpan class.
对于.Net <= 4.0使用TimeSpan类。
TimeSpan t = TimeSpan.FromSeconds( secs );
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use
(如Inder Kumar Rathore所述)对于.NET> 4.0,您可以使用
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");
(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds
to avoid an exception.
(来自Nick Molyneux)确保秒小于TimeSpan.MaxValue.TotalSeconds以避免异常。
#2
For .NET > 4.0 you can use
对于.NET> 4.0,您可以使用
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");
or if you want date time format then you can also do this
或者如果您想要日期时间格式,那么您也可以这样做
TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = date.ToString("hh:mm:tt");
For more you can check Custom TimeSpan Format Strings
有关更多信息,您可以查看自定义TimeSpan格式字符串
#3
If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:
如果您知道有几秒钟,则可以通过调用TimeSpan.FromSeconds来创建TimeSpan值:
TimeSpan ts = TimeSpan.FromSeconds(80);
You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.
然后,您可以获得天数,小时数,分钟数或秒数。或者使用其中一个ToString重载以您喜欢的任何方式输出它。
#4
TimeSpan.FromSeconds(80);
http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx
#5
The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:
TimeSpan构造函数允许您在几秒钟内传递。只需声明一个TimeSpan类型的变量秒。例如:
TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
#6
I did some benchmarks to see what's the fastest way and these are my results and conclusions. I ran each method 10M times and added a comment with the average time per run.
我做了一些基准测试,看看最快的方法是什么,这些是我的结果和结论。我运行了每个方法10M次并添加了评论,每次运行的平均时间。
If your input milliseconds are not limited to one day (your result may be 143:59:59.999), these are the options, from faster to slower:
如果您的输入毫秒不限于一天(您的结果可能是143:59:59.999),这些是从更快到更慢的选项:
// 0.86 ms
static string Method1(int millisecs)
{
int hours = millisecs / 3600000;
int mins = (millisecs % 3600000) / 60000;
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}", hours, mins, millisecs % 60000 / 1000, millisecs % 1000);
}
// 0.89 ms
static string Method2(int millisecs)
{
double s = millisecs % 60000 / 1000.0;
millisecs /= 60000;
int mins = millisecs % 60;
int hours = millisecs / 60;
return string.Format("{0:D2}:{1:D2}:{2:00.000}", hours, mins, s);
}
// 0.95 ms
static string Method3(int millisecs)
{
TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
(int)t.TotalHours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
If your input milliseconds are limited to one day (your result will never be greater then 23:59:59.999), these are the options, from faster to slower:
如果你的输入毫秒数限制为一天(你的结果永远不会超过23:59:59.999),这些是从快到慢的选项:
// 0.58 ms
static string Method5(int millisecs)
{
// Fastest way to create a DateTime at midnight
// Make sure you use the appropriate decimal separator
return DateTime.FromBinary(599266080000000000).AddMilliseconds(millisecs).ToString("HH:mm:ss.fff");
}
// 0.59 ms
static string Method4(int millisecs)
{
// Make sure you use the appropriate decimal separator
return TimeSpan.FromMilliseconds(millisecs).ToString(@"hh\:mm\:ss\.fff");
}
// 0.93 ms
static string Method6(int millisecs)
{
TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
In case your input is just seconds, the methods are slightly faster. Again, if your input seconds are not limited to one day (your result may be 143:59:59):
如果你的输入只是几秒钟,那么方法会稍快一点。同样,如果您的输入秒数不限于一天(您的结果可能是143:59:59):
// 0.63 ms
static string Method1(int secs)
{
int hours = secs / 3600;
int mins = (secs % 3600) / 60;
secs = secs % 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, secs);
}
// 0.64 ms
static string Method2(int secs)
{
int s = secs % 60;
secs /= 60;
int mins = secs % 60;
int hours = secs / 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, s);
}
// 0.70 ms
static string Method3(int secs)
{
TimeSpan t = TimeSpan.FromSeconds(secs);
return string.Format("{0:D2}:{1:D2}:{2:D2}",
(int)t.TotalHours,
t.Minutes,
t.Seconds);
}
And if your input seconds are limited to one day (your result will never be greater then 23:59:59):
如果您的输入秒数限制为一天(您的结果将永远不会超过23:59:59):
// 0.33 ms
static string Method5(int secs)
{
// Fastest way to create a DateTime at midnight
return DateTime.FromBinary(599266080000000000).AddSeconds(secs).ToString("HH:mm:ss");
}
// 0.34 ms
static string Method4(int secs)
{
return TimeSpan.FromSeconds(secs).ToString(@"hh\:mm\:ss");
}
// 0.70 ms
static string Method6(int secs)
{
TimeSpan t = TimeSpan.FromSeconds(secs);
return string.Format("{0:D2}:{1:D2}:{2:D2}",
t.Hours,
t.Minutes,
t.Seconds);
}
As a final comment, let me add that I noticed that string.Format
is a bit faster if you use D2
instead of 00
.
作为最后的评论,让我补充一点,我注意到如果使用D2而不是00,string.Format会更快一些。
#7
I'd suggest you use the TimeSpan
class for this.
我建议你使用TimeSpan类。
public static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromSeconds(80);
Console.WriteLine(t.ToString());
t = TimeSpan.FromSeconds(868693412);
Console.WriteLine(t.ToString());
}
Outputs:
00:01:20
10054.07:43:32
#8
In VB.NET, but it's the same in C#:
在VB.NET中,但它在C#中是一样的:
Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
#9
Why do people need TimeSpan AND DateTime if we have DateTime.AddSeconds()?
如果我们有DateTime.AddSeconds(),为什么人们需要TimeSpan和DateTime?
var dt = new DateTime(2015, 1, 1).AddSeconds(totalSeconds);
The date is arbitrary. totalSeconds can be greater than 59 and it is a double. Then you can format your time as you want using DateTime.ToString():
日期是任意的。 totalSeconds可以大于59,它是一个双倍。然后,您可以使用DateTime.ToString()格式化您的时间:
dt.ToString("H:mm:ss");
This does not work if totalSeconds < 0 or > 59:
如果totalSeconds <0或> 59,则不起作用:
new DateTime(2015, 1, 1, 0, 0, totalSeconds)
#10
For .NET < 4.0 (e.x: Unity) you can write an extension method to have the TimeSpan.ToString(string format)
behavior like .NET > 4.0
对于.NET <4.0(e.x:Unity),您可以编写一个扩展方法,使其具有类似.NET> 4.0的TimeSpan.ToString(字符串格式)行为
public static class TimeSpanExtensions
{
public static string ToString(this TimeSpan time, string format)
{
DateTime dateTime = DateTime.Today.Add(time);
return dateTime.ToString(format);
}
}
And from anywhere in your code you can use it like:
从代码中的任何位置,您都可以使用它:
var time = TimeSpan.FromSeconds(timeElapsed);
string formattedDate = time.ToString("hh:mm:ss:fff");
This way you can format any TimeSpan
object by simply calling ToString from anywhere of your code.
这样,您可以通过从代码的任何位置调用ToString来格式化任何TimeSpanobject。
#11
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");
}
//Test
[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);
}
#12
to get total seconds
获得总秒数
var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;
and to get datetime from seconds
从秒开始获取日期时间
var thatDateTime = new DateTime().AddSeconds(i)
#1
For .Net <= 4.0 Use the TimeSpan class.
对于.Net <= 4.0使用TimeSpan类。
TimeSpan t = TimeSpan.FromSeconds( secs );
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use
(如Inder Kumar Rathore所述)对于.NET> 4.0,您可以使用
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");
(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds
to avoid an exception.
(来自Nick Molyneux)确保秒小于TimeSpan.MaxValue.TotalSeconds以避免异常。
#2
For .NET > 4.0 you can use
对于.NET> 4.0,您可以使用
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");
or if you want date time format then you can also do this
或者如果您想要日期时间格式,那么您也可以这样做
TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = date.ToString("hh:mm:tt");
For more you can check Custom TimeSpan Format Strings
有关更多信息,您可以查看自定义TimeSpan格式字符串
#3
If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:
如果您知道有几秒钟,则可以通过调用TimeSpan.FromSeconds来创建TimeSpan值:
TimeSpan ts = TimeSpan.FromSeconds(80);
You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.
然后,您可以获得天数,小时数,分钟数或秒数。或者使用其中一个ToString重载以您喜欢的任何方式输出它。
#4
TimeSpan.FromSeconds(80);
http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx
#5
The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:
TimeSpan构造函数允许您在几秒钟内传递。只需声明一个TimeSpan类型的变量秒。例如:
TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
#6
I did some benchmarks to see what's the fastest way and these are my results and conclusions. I ran each method 10M times and added a comment with the average time per run.
我做了一些基准测试,看看最快的方法是什么,这些是我的结果和结论。我运行了每个方法10M次并添加了评论,每次运行的平均时间。
If your input milliseconds are not limited to one day (your result may be 143:59:59.999), these are the options, from faster to slower:
如果您的输入毫秒不限于一天(您的结果可能是143:59:59.999),这些是从更快到更慢的选项:
// 0.86 ms
static string Method1(int millisecs)
{
int hours = millisecs / 3600000;
int mins = (millisecs % 3600000) / 60000;
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}", hours, mins, millisecs % 60000 / 1000, millisecs % 1000);
}
// 0.89 ms
static string Method2(int millisecs)
{
double s = millisecs % 60000 / 1000.0;
millisecs /= 60000;
int mins = millisecs % 60;
int hours = millisecs / 60;
return string.Format("{0:D2}:{1:D2}:{2:00.000}", hours, mins, s);
}
// 0.95 ms
static string Method3(int millisecs)
{
TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
(int)t.TotalHours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
If your input milliseconds are limited to one day (your result will never be greater then 23:59:59.999), these are the options, from faster to slower:
如果你的输入毫秒数限制为一天(你的结果永远不会超过23:59:59.999),这些是从快到慢的选项:
// 0.58 ms
static string Method5(int millisecs)
{
// Fastest way to create a DateTime at midnight
// Make sure you use the appropriate decimal separator
return DateTime.FromBinary(599266080000000000).AddMilliseconds(millisecs).ToString("HH:mm:ss.fff");
}
// 0.59 ms
static string Method4(int millisecs)
{
// Make sure you use the appropriate decimal separator
return TimeSpan.FromMilliseconds(millisecs).ToString(@"hh\:mm\:ss\.fff");
}
// 0.93 ms
static string Method6(int millisecs)
{
TimeSpan t = TimeSpan.FromMilliseconds(millisecs);
// Make sure you use the appropriate decimal separator
return string.Format("{0:D2}:{1:D2}:{2:D2}.{3:D3}",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
}
In case your input is just seconds, the methods are slightly faster. Again, if your input seconds are not limited to one day (your result may be 143:59:59):
如果你的输入只是几秒钟,那么方法会稍快一点。同样,如果您的输入秒数不限于一天(您的结果可能是143:59:59):
// 0.63 ms
static string Method1(int secs)
{
int hours = secs / 3600;
int mins = (secs % 3600) / 60;
secs = secs % 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, secs);
}
// 0.64 ms
static string Method2(int secs)
{
int s = secs % 60;
secs /= 60;
int mins = secs % 60;
int hours = secs / 60;
return string.Format("{0:D2}:{1:D2}:{2:D2}", hours, mins, s);
}
// 0.70 ms
static string Method3(int secs)
{
TimeSpan t = TimeSpan.FromSeconds(secs);
return string.Format("{0:D2}:{1:D2}:{2:D2}",
(int)t.TotalHours,
t.Minutes,
t.Seconds);
}
And if your input seconds are limited to one day (your result will never be greater then 23:59:59):
如果您的输入秒数限制为一天(您的结果将永远不会超过23:59:59):
// 0.33 ms
static string Method5(int secs)
{
// Fastest way to create a DateTime at midnight
return DateTime.FromBinary(599266080000000000).AddSeconds(secs).ToString("HH:mm:ss");
}
// 0.34 ms
static string Method4(int secs)
{
return TimeSpan.FromSeconds(secs).ToString(@"hh\:mm\:ss");
}
// 0.70 ms
static string Method6(int secs)
{
TimeSpan t = TimeSpan.FromSeconds(secs);
return string.Format("{0:D2}:{1:D2}:{2:D2}",
t.Hours,
t.Minutes,
t.Seconds);
}
As a final comment, let me add that I noticed that string.Format
is a bit faster if you use D2
instead of 00
.
作为最后的评论,让我补充一点,我注意到如果使用D2而不是00,string.Format会更快一些。
#7
I'd suggest you use the TimeSpan
class for this.
我建议你使用TimeSpan类。
public static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromSeconds(80);
Console.WriteLine(t.ToString());
t = TimeSpan.FromSeconds(868693412);
Console.WriteLine(t.ToString());
}
Outputs:
00:01:20
10054.07:43:32
#8
In VB.NET, but it's the same in C#:
在VB.NET中,但它在C#中是一样的:
Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
#9
Why do people need TimeSpan AND DateTime if we have DateTime.AddSeconds()?
如果我们有DateTime.AddSeconds(),为什么人们需要TimeSpan和DateTime?
var dt = new DateTime(2015, 1, 1).AddSeconds(totalSeconds);
The date is arbitrary. totalSeconds can be greater than 59 and it is a double. Then you can format your time as you want using DateTime.ToString():
日期是任意的。 totalSeconds可以大于59,它是一个双倍。然后,您可以使用DateTime.ToString()格式化您的时间:
dt.ToString("H:mm:ss");
This does not work if totalSeconds < 0 or > 59:
如果totalSeconds <0或> 59,则不起作用:
new DateTime(2015, 1, 1, 0, 0, totalSeconds)
#10
For .NET < 4.0 (e.x: Unity) you can write an extension method to have the TimeSpan.ToString(string format)
behavior like .NET > 4.0
对于.NET <4.0(e.x:Unity),您可以编写一个扩展方法,使其具有类似.NET> 4.0的TimeSpan.ToString(字符串格式)行为
public static class TimeSpanExtensions
{
public static string ToString(this TimeSpan time, string format)
{
DateTime dateTime = DateTime.Today.Add(time);
return dateTime.ToString(format);
}
}
And from anywhere in your code you can use it like:
从代码中的任何位置,您都可以使用它:
var time = TimeSpan.FromSeconds(timeElapsed);
string formattedDate = time.ToString("hh:mm:ss:fff");
This way you can format any TimeSpan
object by simply calling ToString from anywhere of your code.
这样,您可以通过从代码的任何位置调用ToString来格式化任何TimeSpanobject。
#11
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");
}
//Test
[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);
}
#12
to get total seconds
获得总秒数
var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;
and to get datetime from seconds
从秒开始获取日期时间
var thatDateTime = new DateTime().AddSeconds(i)