你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

单片机RTC时间转为Unix时间戳

[复制链接]
wofei1314 发布时间:2017-3-23 10:28
最近因工作需要把单片机的YYMMDDHHMMSS转为Unix的时间戳,网上大多都是上位机的程序,经过搜索引擎的帮助下,终于实现了把单片机的时间转为Unix的时间戳,特贴出代码给社区内需要的朋友,转载请注明出处!!!

由于使用了 struct tm 结构体好是mktime,所以需要包含 <time.h>头文件,把下面的年月日时分秒换成实际的年月日时分秒即可!
废话不多说,核心代码:
  1. int32_t GetTick(void)  
  2. {  
  3.     struct tm stm;  
  4.     int iY, iM, iD, iH, iMin, iS;  
  5.        
  6.         RTC_DateTypeDef sdatestructureget;
  7.         RTC_TimeTypeDef stimestructureget;

  8.         /* Get the RTC current Time */
  9.         HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
  10.         /* Get the RTC current Date */
  11.         HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);
  12.   
  13.     memset(&stm,0,sizeof(stm));  

  14.        
  15.         iY = sdatestructureget.Year;  
  16.     iM = sdatestructureget.Month;  
  17.     iD = sdatestructureget.Date;  
  18.     iH = stimestructureget.Hours-8;//北京时间-8=UTC  
  19.     iMin = stimestructureget.Minutes;  
  20.     iS = stimestructureget.Seconds;

  21.   
  22.     stm.tm_year=iY+100;
  23.     stm.tm_mon=iM-1;  
  24.     stm.tm_mday=iD;  
  25.     stm.tm_hour=iH;  
  26.     stm.tm_min=iMin;  
  27.     stm.tm_sec=iS;  

  28.     return mktime(&stm);  
  29. }
复制代码
收藏 1 评论9 发布时间:2017-3-23 10:28

举报

9个回答
请叫我小张张 回答时间:2017-3-23 10:32:35
点赞
斜阳 回答时间:2017-3-23 10:34:30
赞                              
JeffJiang 回答时间:2017-3-23 10:35:21
赞赞赞
wofei1314 回答时间:2017-3-23 10:43:33
多谢各位捧场~
我姓罗 回答时间:2018-6-12 15:44:18
你这个应该有问题吧    首先年份上应该减去1900   月份上减一     
So_cracy 回答时间:2018-6-28 16:09:07
我姓罗 发表于 2018-6-12 15:44
你这个应该有问题吧    首先年份上应该减去1900   月份上减一

实测没毛病,这是HAL库,不懂别乱说
any012 回答时间:2018-12-4 16:12:25
正好用到,感谢。
要是把时间戳转本地时间的函数也写出来就更好了。
熊猫仙 回答时间:2019-7-3 09:24:15
mktime(&stm),这句话很费资源啊
徐家阔少 回答时间:2023-2-23 15:33:04

typedef unsigned int time_t; / date/time in unix secs past 1-Jan-70 /

extern _ARMABI time_t mktime(struct tm /timeptr*/) attribute((nonnull(1)));

//本地时间生成时间戳函数 uint32_t TimeToTimeStamp(void) { struct tm stm; memset(&stm,0,sizeof(stm)); stm.tm_year = TimeData.year - 1900; //RTC_Year rang 0-9999,but tm_year since 1900 stm.tm_mon = TimeData.month - 1; //RTC_Month rang 1-12,but tm_mon rang 0-11 stm.tm_mday = TimeData.day; //RTC_Date rang 1-31 and tm_mday rang 1-31 stm.tm_hour = TimeData.hour - 8; //RTC_Hours rang 0-23 and tm_hour rang 0-23 stm.tm_min = TimeData.minute; //RTC_Minutes rang 0-59 and tm_min rang 0-59 stm.tm_sec = TimeData.second; return mktime(&stm); }

所属标签

关于
我们是谁
投资者关系
意法半导体可持续发展举措
创新与技术
意法半导体官网
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
官方最新发布
STM32N6 AI生态系统
STM32MCU,MPU高性能GUI
ST ACEPACK电源模块
意法半导体生物传感器
STM32Cube扩展软件包
关注我们
st-img 微信公众号
st-img 手机版