C# 如何编写以秒为单位获取值并以小时、分钟和秒为单位打印的方法
好的,这是我关于StackOverflow的第一个问题,我看到评论不是很好(在我有机会修复之前,帖子一直被删除)。给我一个机会!我的理解是,问题应该尽可能直接,而不是制造“讨论” 这是我已经尝试过的,但是输出不是我期望的C# 如何编写以秒为单位获取值并以小时、分钟和秒为单位打印的方法,c#,C#,好的,这是我关于StackOverflow的第一个问题,我看到评论不是很好(在我有机会修复之前,帖子一直被删除)。给我一个机会!我的理解是,问题应该尽可能直接,而不是制造“讨论” 这是我已经尝试过的,但是输出不是我期望的 int secondsToHours(seconds) { int totalSec = seconds; int hrs = totalSec % 3600; int secs = totalSec % 60; int mins = totalSec / 60; stri
int secondsToHours(seconds) {
int totalSec = seconds;
int hrs = totalSec % 3600;
int secs = totalSec % 60;
int mins = totalSec / 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}
你可以用一个物体
你可以用一个物体
您可以使用TimeSpan结构:
TimeSpan ts = TimeSpan.FromSeconds(seconds);
然后生成所需的字符串:
ts.ToString(@"hh\:mm\:ss")
您可以使用TimeSpan结构:
TimeSpan ts = TimeSpan.FromSeconds(seconds);
然后生成所需的字符串:
ts.ToString(@"hh\:mm\:ss")
看看TimeSpan类
TimeSpan span = TimeSpan.FromSeconds(total seconds here);
然后查看Days、Hours、Minutes和Seconds属性,或TotalDays、TotalHours等查看TimeSpan类
TimeSpan span = TimeSpan.FromSeconds(total seconds here);
然后查看Days、Hours、Minutes和Seconds属性,或者TotalDays、TotalHours等最简单的方法是使用
TimeSpan
,正如前面的答案中所建议的那样,但如果您想使用Math
进行此操作,也可以尝试:
private static void secondsToHours(int seconds)
{
int hrs = seconds / 3600;
int remainder = seconds % 3600;
int mins = remainder / 60;
int secs = seconds % 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}
最简单的方法是使用
TimeSpan
,正如前面的答案中所建议的那样,但如果您想使用Math
,也可以尝试此方法:
private static void secondsToHours(int seconds)
{
int hrs = seconds / 3600;
int remainder = seconds % 3600;
int mins = remainder / 60;
int secs = seconds % 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}
您需要从
totalSec
中减去。以4700
为例
int left;
int hrs = totalSec / 3600; // hrs will be 1
left = totalSec - hrs * 3600; //left will be 1100
int mins = left / 60; //mins will be 18
left = left - mins * 60; // left will be 20
int secs = left; // secs will be 20
作为解决方案,4700
将是1小时18分20秒
但在这种情况下,使用它会更好。你可以用like
您需要从
totalSec
中减去。以4700
为例
int left;
int hrs = totalSec / 3600; // hrs will be 1
left = totalSec - hrs * 3600; //left will be 1100
int mins = left / 60; //mins will be 18
left = left - mins * 60; // left will be 20
int secs = left; // secs will be 20
作为解决方案,4700
将是1小时18分20秒
但在这种情况下,使用它会更好。你可以用like