首页 后端开发 C++ 如何在 C 中将表示时间的字符串转换为'time_t”?

如何在 C 中将表示时间的字符串转换为'time_t”?

Nov 10, 2024 am 07:41 AM

How to Convert a String Representing Time to a `time_t` in C  ?

将表示时间的字符串转换为 C 中的 time_t

在 C 中处理时间时,您可能会遇到这样的情况:您有一个字符串表示特定时间,需要将其转换为可移植的 time_t 数据类型。 time_t 类型表示自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的秒数。

转换为 time_t

在 C 11 及更高版本中,std::get_time 函数可用于将字符串解析为 std::tm 结构,然后可以将其转换为 time_t 使用 mktime:

#include <iostream>
#include <sstream>
#include <time.h>

int main() {
  std::string time_details = "16:35:12";
  std::tm tm;
  std::istringstream ss(time_details);
  ss >> std::get_time(&tm, "%H:%M:%S");
  std::time_t time = mktime(&tm);

  // Print the converted time_t
  std::cout << "Converted time: " << time << std::endl;

  return 0;
}
登录后复制

比较两次

一旦您在 time_t 中有多个时间格式,您可以比较它们以确定哪个较早。

#include <iostream>
#include <time.h>

int main() {
  std::string curr_time = "18:35:21"; // Current time
  std::string user_time = "22:45:31"; // User's time
  std::tm curr_tm, user_tm;
  std::istringstream ss;

  // Parse both times
  ss.str(curr_time);
  ss >> std::get_time(&curr_tm, "%H:%M:%S");
  ss.clear();
  ss.str(user_time);
  ss >> std::get_time(&user_tm, "%H:%M:%S");

  // Compare the time_t values
  std::time_t curr_secs = mktime(&curr_tm);
  std::time_t user_secs = mktime(&user_tm);

  if (curr_secs < user_secs) {
    std::cout << "Current time is earlier than user's time" << std::endl;
  } else {
    std::cout << "User's time is earlier than current time" << std::endl;
  }

  return 0;
}
登录后复制

以上是如何在 C 中将表示时间的字符串转换为'time_t”?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章

仓库:如何复兴队友
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前 By 尊渡假赌尊渡假赌尊渡假赌

热门文章

仓库:如何复兴队友
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前 By 尊渡假赌尊渡假赌尊渡假赌

热门文章标签

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Gulc:从头开始建造的C库 Gulc:从头开始建造的C库 Mar 03, 2025 pm 05:46 PM

Gulc:从头开始建造的C库

c语言函数返回值的类型有哪些?返回值是由什么决定的? c语言函数返回值的类型有哪些?返回值是由什么决定的? Mar 03, 2025 pm 05:52 PM

c语言函数返回值的类型有哪些?返回值是由什么决定的?

c语言函数格式字母大小写转换步骤 c语言函数格式字母大小写转换步骤 Mar 03, 2025 pm 05:53 PM

c语言函数格式字母大小写转换步骤

c语言函数的定义和调用规则是什么 c语言函数的定义和调用规则是什么 Mar 03, 2025 pm 05:53 PM

c语言函数的定义和调用规则是什么

distinct用法和短语分享 distinct用法和短语分享 Mar 03, 2025 pm 05:51 PM

distinct用法和短语分享

c语言函数返回值在内存保存在哪里? c语言函数返回值在内存保存在哪里? Mar 03, 2025 pm 05:51 PM

c语言函数返回值在内存保存在哪里?

C标准模板库(STL)如何工作? C标准模板库(STL)如何工作? Mar 12, 2025 pm 04:50 PM

C标准模板库(STL)如何工作?

如何有效地使用STL(排序,查找,转换等)的算法? 如何有效地使用STL(排序,查找,转换等)的算法? Mar 12, 2025 pm 04:52 PM

如何有效地使用STL(排序,查找,转换等)的算法?

See all articles