最近因工作需要把单片机的YYMMDDHHMMSS转为Unix的时间戳,网上大多都是上位机的程序,经过搜索引擎的帮助下,终于实现了把单片机的时间转为Unix的时间戳,特贴出代码给社区内需要的朋友,转载请注明出处!!!
- M' Y& M T5 c9 a1 H" k( V6 L$ C- s" U& H
由于使用了 struct tm 结构体好是mktime,所以需要包含 <time.h>头文件,把下面的年月日时分秒换成实际的年月日时分秒即可!
# _; B8 L$ o# z" o+ E1 [: E; I废话不多说,核心代码:' g3 e; ? i6 S: O% O9 C, W2 I
- int32_t GetTick(void)
7 Z+ K% j, m5 o2 o& P( Z - { 5 O' d' A9 @2 L; G, P* |( d
- struct tm stm;
/ _9 | t1 t( Z1 o: f& x7 d0 i - int iY, iM, iD, iH, iMin, iS; - u' O# _0 t- v$ z
- # O' N, w6 U8 U3 ^
- RTC_DateTypeDef sdatestructureget;
: d. \' ^6 j+ l# J - RTC_TimeTypeDef stimestructureget;# @% l9 S9 Z$ }$ g P* x
3 a0 O' K; L/ R; K- /* Get the RTC current Time */, g6 {: Q, I, T
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
7 @- W! K3 H# M- S+ M, g - /* Get the RTC current Date */
" W# q5 ^& m3 Y' @; ~" V1 i7 v - HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);9 ?2 T/ |- N2 G5 U, w2 U1 |& z
-
5 z4 p0 n, \$ Y y* M- ] - memset(&stm,0,sizeof(stm)); 4 M& @- M" f5 v
- ) t) E4 W3 `5 l4 z
-
* ^. E4 z8 a% |" U( F - iY = sdatestructureget.Year; 7 `% ~. K, p( j* Y$ ~
- iM = sdatestructureget.Month;
0 v( d3 E0 Y# k) f c( W - iD = sdatestructureget.Date;
6 p0 l6 h) s/ a k' P5 d2 X/ I - iH = stimestructureget.Hours-8;//北京时间-8=UTC
5 m' W( H3 y% O5 |7 ?% W1 G - iMin = stimestructureget.Minutes; 7 z/ p" K! }1 r- F* K0 a
- iS = stimestructureget.Seconds;
& F# j9 I" L7 @' y) @# _' r
% w) K" H ]9 d4 O& v- ( n$ ?) \6 J' _
- stm.tm_year=iY+100;% d, z: R' k) g9 {2 A6 W
- stm.tm_mon=iM-1;
+ C: q7 R8 e0 x" Y' y - stm.tm_mday=iD;
5 y3 ^' P9 {8 v2 S8 j# w, X - stm.tm_hour=iH; + L" d5 I" f6 O. s1 W9 b T7 b
- stm.tm_min=iMin;
; l$ Q y" \2 s1 H - stm.tm_sec=iS; + k+ z7 y. c6 n$ i3 D
/ [& ?) {# S7 B. u9 m5 u* A- o: n- return mktime(&stm); 4 ^; q; P6 e9 a+ `4 L: t S
- }
复制代码 |
实测没毛病,这是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); }