C语言 UTC时间转化为北京时间

前言:程序获取的代码有时候为UTC英国伦敦格林尼治时间,我们并不能拿到手直接用,所以要经过特殊的代码转化才可以使用,以下为代码的处理:utc转化为北京时间(+8h)。 太阳东升西落,所以北京的时间比UTC的时间相比是(+8H),东半球是11号8:00,西半球还是10号24:00

代码逻辑图

mktime() 是 C 语言 <time.h> 头文件中的核心时间函数,核心作用是将本地时间的 struct tm 结构体转换为 UTC 时间戳(time_t 类型,即从 1970-01-01 00:00:00 UTC 到该时间的秒数) ,同时还会自动修正 struct tm 中不合法的时间字段(比如月份 13、日期 32 等)。

cpp 复制代码
time_t mktime(struct tm *tm_ptr);

作用 :把 time_t 类型的 UTC 时间戳(从 1970-01-01 00:00:00 UTC 到当前的秒数)转换为本地时区struct tm 结构体(比如北京时间,东八区)
localtime() 是编程中用于处理时间的核心函数,不同编程语言(C/C++、Python 等)都有实现,核心作用是将 UTC 时间戳(秒数)转换为对应时区的本地时间结构体 / 对象(包含年、月、日、时、分、秒等字段)

cpp 复制代码
struct tm *localtime(const time_t *timer);
  • 参数tm_ptr → 指向本地时间 struct tm 结构体的指针(需传入年、月、日、时、分、秒等字段);
cpp 复制代码
  uint16_t year = 2024;
  uint8_t month = 6;
  uint8_t date1 = 2;
  uint8_t hour = 7;
  uint8_t min = 8;
  uint8_t sec = 22;

  //utc时间
  struct tm utc_time;
  utc_time.tm_year = year - 1900;
  utc_time.tm_mon  = month-1;
  utc_time.tm_mday = date1;
  utc_time.tm_hour = hour;
  utc_time.tm_min = min;
  utc_time.tm_sec = sec;

  time_t secs = mktime(&utc_time);

  secs = secs+60*60*8;
  //北京时间
  struct tm *bj_time = localtime(&secs);
  
  uint8_t date_string[20] = {0};
  sprintf((char *)date_string, "%d-%02d-%02d %02d:%02d:%02d",
          bj_time->tm_year + 1900, 
          bj_time->tm_mon + 1, 
          bj_time->tm_mday, 
          bj_time->tm_hour, 
          bj_time->tm_min, 
          bj_time->tm_sec 
          
        );
  debug_printfln("date = %s", date_string);
相关推荐
晓蛋1 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
傲世仙尊1 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
牵猫散步的鱼儿1 天前
重载、重写(覆盖)、重定义区别
c语言
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
phltxy1 天前
C 语言指针:从内存地址到灵活的数据访问
c语言
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
phltxy1 天前
C 语言中的数据存储:从类型到二进制位
c语言
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超1 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust