【问题标题】:Given an integer time in the format hhmmss how can it be formatted to hh:mm:ss给定格式为 hhmmss 的整数时间,如何将其格式化为 hh:mm:ss
【发布时间】:2014-04-22 03:40:18
【问题描述】:

我正在尝试将C中的时间戳拆分为合适的格式,该格式为hh:mm:ss

时间戳以hhmmss 格式存储为正整数。有没有办法在 C 中格式化它?

我没有要显示的代码,因为我不知道从哪里开始,我的想法是将时间戳存储在一个字符数组中,然后每 2 个字符打印一个 ':' 字符。

示例输出:

timestamp = 123456

我希望它显示为12:34:56

timestamp = 010203

我希望它显示为01:02:03

【问题讨论】:

    标签: c time timestamp


    【解决方案1】:
    int timestamp = 10203;
    int hour = timestamp / 10000;
    int minute = timestamp % 10000 / 100;
    int second = timestamp % 100;
    
    printf("%02d:%02d:%02d\n", hour, minute, second);
    

    当时间戳以0 开头时要小心,因为010203 是一个八位字节整数文字,结果可能与您的预期不同。

    【讨论】:

      【解决方案2】:

      您可以使用整数除法将数字拆分为您喜欢的方式。

      例如,要获得您可以做的秒数

      seconds = timestamp % 100
      

      为了得到你可以得到的分钟

      minutes = (timestamp / 100) % 100
      

      然后您可以使用printf 以您喜欢的任何格式打印出时间。

      例如

      printf("%02d:%02d", minutes, seconds);
      

      【讨论】:

      • 和时间戳 / 10000 小时
      • 留作读者练习。我试图展示如何去做,而不是真正去做。
      猜你喜欢
      • 2019-07-01
      • 1970-01-01
      • 2017-01-06
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      相关资源
      最近更新 更多