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);
相关推荐
祈安_2 天前
C语言内存函数
c语言·后端
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法