21xrx.com
2024-05-20 07:42:21 Monday
登录
文章检索 我的文章 写文章
C++ 时间格式转换技巧
2023-07-13 08:00:54 深夜i     --     --
C++ 时间格式 转换技巧 时间戳 日期时间

在C++编程中,涉及到时间处理时,不可避免地需要进行时间格式转换操作。下面介绍一些C++中常用的时间格式转换技巧。

1. Unix时间戳与日期时间相互转换

Unix时间戳,也称为Epoch时间,是指自1970年1月1日0时0分0秒到某个时间点之间所经过的秒数。在C++中,可以使用time()函数获取当前时间的Unix时间戳。

Unix时间戳和日期时间可以相互转换,以下是Unix时间戳转换为日期时间的代码实现:


#include <time.h>

#include <iostream>

using namespace std;

int main()

{

  time_t now = time(0); // 获取当前时间

  tm *ltm = localtime(&now);

  cout << "Year: " << 1900 + ltm->tm_year << endl; // 年份需要加上1900

  cout << "Month: " << 1 + ltm->tm_mon << endl; // 月份需要加1

  cout << "Day: " << ltm->tm_mday << endl;

  cout << "Time: " << ltm->tm_hour << ":";

  cout << ltm->tm_min << ":";

  cout << ltm->tm_sec << endl;

  return 0;

}

以下是日期时间转换为Unix时间戳的代码实现:


#include <time.h>

#include <iostream>

using namespace std;

int main()

{

  tm t = {0}; // 初始化tm结构体变量

  // 设置年月日时分秒

  t.tm_year = 2021 - 1900;

  t.tm_mon = 8 - 1;

  t.tm_mday = 18;

  t.tm_hour = 8;

  t.tm_min = 0;

  t.tm_sec = 0;

  time_t utc_time = mktime(&t); // 转换为Unix时间戳

  cout << "Unix time stamp: " << utc_time << endl;

  return 0;

}

2. 字符串时间与日期时间相互转换

在C++中,可以使用strftime()函数将tm结构体表示的日期时间转换为指定格式的字符串。以下是将日期时间转换为字符串的代码实现:


#include <time.h>

#include <iostream>

using namespace std;

int main()

{

  tm t = {0}; // 初始化tm结构体变量

  // 设置年月日时分秒

  t.tm_year = 2021 - 1900;

  t.tm_mon = 8 - 1;

  t.tm_mday = 18;

  t.tm_hour = 8;

  t.tm_min = 0;

  t.tm_sec = 0;

  char buffer[80];

  strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &t); // 转换为指定格式的字符串

  cout << "String format: " << buffer << endl;

  return 0;

}

反之,也可以使用sscanf()函数将字符串转换为tm结构体表示的日期时间。以下是将字符转换为日期时间的代码实现:


#include <time.h>

#include <iostream>

using namespace std;

int main()

{

  tm t = {0}; // 初始化tm结构体变量

  char buffer[80] = "2021-08-18 08:00:00";

  sscanf(buffer, "%d-%d-%d %d:%d:%d",

      &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec); // 转换为tm结构体表示的日期时间

  t.tm_year -= 1900; // 年份需要减去1900

  t.tm_mon -= 1; // 月份需要减1

  cout << "Year: " << 1900 + t.tm_year << endl;

  cout << "Month: " << 1 + t.tm_mon << endl;

  cout << "Day: " << t.tm_mday << endl;

  cout << "Time: " << t.tm_hour << ":";

  cout << t.tm_min << ":";

  cout << t.tm_sec << endl;

  return 0;

}

总结

以上是C++中常用的时间格式转换技巧,掌握这些技巧可以避免在时间处理时出现错误,提高程序的可靠性和可维护性。需要注意的是,在转换时需要考虑时区和夏令时等因素,避免出现时间偏差。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复