最近因工作需要把单片机的YYMMDDHHMMSS转为Unix的时间戳,网上大多都是上位机的程序,经过搜索引擎的帮助下,终于实现了把单片机的时间转为Unix的时间戳,特贴出代码给社区内需要的朋友,转载请注明出处!!!
由于使用了 struct tm 结构体好是mktime,所以需要包含 <time.h>头文件,把下面的年月日时分秒换成实际的年月日时分秒即可!
废话不多说,核心代码:
- int32_t GetTick(void)
- {
- struct tm stm;
- int iY, iM, iD, iH, iMin, iS;
-
- RTC_DateTypeDef sdatestructureget;
- RTC_TimeTypeDef stimestructureget;
- /* Get the RTC current Time */
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
- /* Get the RTC current Date */
- HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);
-
- memset(&stm,0,sizeof(stm));
-
-
- iY = sdatestructureget.Year;
- iM = sdatestructureget.Month;
- iD = sdatestructureget.Date;
- iH = stimestructureget.Hours-8;//北京时间-8=UTC
- iMin = stimestructureget.Minutes;
- iS = stimestructureget.Seconds;
-
- stm.tm_year=iY+100;
- stm.tm_mon=iM-1;
- stm.tm_mday=iD;
- stm.tm_hour=iH;
- stm.tm_min=iMin;
- stm.tm_sec=iS;
- return mktime(&stm);
- }
复制代码 |
实测没毛病,这是HAL库,不懂别乱说
要是把时间戳转本地时间的函数也写出来就更好了。
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); }