c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒

c++实现一个函数,对一个输入的整数,代表时间秒数,将其转换成时间格式字符串,如“01:09:11“,代表1小时,09分,11秒。

#include <iostream>
#include <string>
#include <iomanip> // For std::setw and std::setfill

std::string convertSecondsToTimeString(int seconds) {

  if (seconds > 86400) { // Check if seconds exceed 24 hours
    return "Error: Input exceeds maximum of 24 hours.";
  }
  
  int hours = seconds / 3600; // Calculate the hours
  seconds %= 3600; // Remaining seconds after removing full hours
  int minutes = seconds / 60; // Calculate the minutes
  seconds %= 60; // Remaining seconds

  // Create an ostringstream to format the output
  std::ostringstream timeStream;
  // Set the width to 2 for each part and fill with '0' if needed
  timeStream << std::setw(2) << std::setfill('0') << hours << ":"
    << std::setw(2) << std::setfill('0') << minutes << ":"
    << std::setw(2) << std::setfill('0') << seconds;

  return timeStream.str();
}

int main() {
  int seconds = 2991; // Example input
  std::string timeString = convertSecondsToTimeString(seconds);
  std::cout << "Time in hh:mm:ss format: " << timeString << std::endl;

  int seconds1 = 11126991; // Example input
  std::string timeString1 = convertSecondsToTimeString(seconds1);
  std::cout << "Time in hh:mm:ss format: " << timeString1 << std::endl;
  return 0;
}

输出结果:

Time in hh:mm:ss format: 00:49:51
Time in hh:mm:ss format: Error: Input exceeds maximum of 24 hours.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 C++ 函数,可以将 hhmm.ss utc 格式时间转换为本地时间: ```cpp #include <iostream> #include <iomanip> #include <ctime> using namespace std; time_t utc_to_local_time(const string& utc_time) { int hh, mm; double ss; char sign; sscanf(utc_time.c_str(), "%2d%2d.%lf %c", &hh, &mm, &ss, &sign); int offset = (sign == '-' ? -1 : 1) * (hh * 3600 + mm * 60 + (int)ss); time_t t = time(NULL); tm* local_time = localtime(&t); time_t local_t = mktime(local_time); local_t -= offset; return local_t; } int main() { string utc_time = "0800.00 +"; time_t local_t = utc_to_local_time(utc_time); tm* local_time = localtime(&local_t); cout << "Local Time: " << put_time(local_time, "%Y-%m-%d %H:%M:%S") << endl; return 0; } ``` 函数 `utc_to_local_time` 接受一个字符串,其中包含 hhmm.ss utc 格式时间。该函数首先使用 `sscanf` 函数字符串中提取出小时、分钟、秒和时区符号,并将其转换整数和浮点数表示。然后,该函数计算出本地时间与 UTC 时间之间的偏移量,并使用 `mktime` 函数将本地时间转换时间戳。最后,该函数时间戳中减去偏移量,以获得 UTC 时间对应的本地时间函数返回本地时间时间戳。 在主函数中,我们调用 `utc_to_local_time` 函数,并使用 `localtime` 函数将返回的时间转换为本地时间。然后,我们使用 `put_time` 函数将本地时间格式化为字符串,并输出到控制台上。 注意,该函数假设 hhmm.ss utc 格式时间中的小时、分钟和秒数都是有效的,因此没有进行任何错误检查。在实际的应用程序中,您可能需要添加更多的错误处理代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值