【问题标题】:How to convert total seconds value to string in 'hours minutes seconds' format [duplicate]如何将总秒值转换为“时分秒”格式的字符串[重复]
【发布时间】:2014-07-20 13:00:06
【问题描述】:

我正在尝试将秒转换为小时、分钟和秒。

例子:

int totalseconds = 5049;

如何使用一个消息框在表单中显示结果:

H:1 M:24 S:9

【问题讨论】:

  • 你在哪里卡住了?除以 60?

标签: c#


【解决方案1】:
  var timeSpan = TimeSpan.FromSeconds(5049);
    int hr = timeSpan.Hours;
    int mn = timeSpan.Minutes;
    int sec = timeSpan.Seconds;
    MessageBox.Show("H:" + hr + " M:" + mn + " S:" + sec);

【讨论】:

    【解决方案2】:

    试试这个:

    MessageBox message = new MessageBox();
    int totalseconds = 5049;
    int hours = totalSeconds / 3600;
    int minutes = (totalSeconds % 3600) / 60;
    int seconds = (totalSeconds % 3600) % 60;
    message.ShowDialog(string.Format("{0}:{1}:{2}", hours, minutes, seconds));
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您可以使用 TimeSpan:

      var ts = TimeSpan.FromSeconds(totalsecond);
      
      MessageBox.Show(string.Format("H: {0} M:{1} S:{2}", ts.Hours, ts.Minutes, ts.Seconds));
      

      【讨论】:

      • 你应该使用TotalHours而不是Hours,以防秒数超过1天。
      【解决方案4】:

      使用TimeSpan从秒转换,

          var timeSpan = TimeSpan.FromSeconds(5049);
          int hh = timeSpan.Hours;
          int mm = timeSpan.Minutes;
          int ss = timeSpan.Seconds;
          MessageBox.Show("Hours" + hh + " Minutes" + mm + " Seconds" + ss);
      

      【讨论】:

        猜你喜欢
        • 2013-06-08
        • 2021-01-14
        • 1970-01-01
        • 2019-07-04
        • 1970-01-01
        • 2021-07-19
        • 2021-01-28
        • 2014-01-29
        • 1970-01-01
        相关资源
        最近更新 更多