最近因工作需要把单片机的YYMMDDHHMMSS转为Unix的时间戳,网上大多都是上位机的程序,经过搜索引擎的帮助下,终于实现了把单片机的时间转为Unix的时间戳,特贴出代码给社区内需要的朋友,转载请注明出处!!!
) g% q x; ]# C
% K/ c( G# c' y: K! T, j6 t由于使用了 struct tm 结构体好是mktime,所以需要包含 <time.h>头文件,把下面的年月日时分秒换成实际的年月日时分秒即可!. P7 ~( v( d2 V5 c l. d! @
废话不多说,核心代码:
; D! [0 l9 ?' [9 J+ ~/ c0 w0 n9 w- int32_t GetTick(void)
# T/ y' i& S" u - { 1 f4 l6 S) p( f0 a
- struct tm stm; 8 L# m4 {* E5 r8 Q9 J
- int iY, iM, iD, iH, iMin, iS;
% v) e- {* J; D6 C# f - 5 c4 l4 C9 z/ f" {" u3 R
- RTC_DateTypeDef sdatestructureget;
9 l4 [ s, ~, ? - RTC_TimeTypeDef stimestructureget;2 D, d% K" v$ V2 l
2 F! b5 s' N3 X8 t6 W9 s9 G, @- /* Get the RTC current Time */& Z' S9 J( }; I/ m. R% L0 N/ n( x
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
/ }# u; c; ~2 G n - /* Get the RTC current Date */# S. R- |; v. ^3 {# O5 W6 z
- HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);) N. |8 i7 Q% v9 i. }, ~
- 5 ~8 a; q& b; p- V
- memset(&stm,0,sizeof(stm));
" }2 J6 [" K6 t/ N9 [1 O8 I -
) ]" {0 \. z% T3 Z8 L - $ X1 t* t, Z9 t1 P
- iY = sdatestructureget.Year;
- t% q, }) t& [4 o$ {* _6 s - iM = sdatestructureget.Month;
; C9 T. b* N# A; e7 n& H - iD = sdatestructureget.Date;
: n- {. C! n, c* @4 b$ q - iH = stimestructureget.Hours-8;//北京时间-8=UTC 6 v& y- V9 J. ]* l) O/ R) E
- iMin = stimestructureget.Minutes; ' a- w, M7 e/ s1 W6 [0 U7 O, @" k
- iS = stimestructureget.Seconds;
6 O l: k- J8 [ J' F - / `5 @9 g2 h6 [
-
/ C! |7 v! @' y+ B# Q. y - stm.tm_year=iY+100;
: g! R2 |( [& @+ X f' j4 S - stm.tm_mon=iM-1; + M' G, g0 D. N, O$ L5 F% w
- stm.tm_mday=iD;
% D% {5 D- @# K" l& q" H1 |; P - stm.tm_hour=iH; 4 u2 ? p6 q/ U% K- N# Q% U2 f
- stm.tm_min=iMin; & X6 [) N: J( q
- stm.tm_sec=iS;
8 X4 e) u- i9 J7 {; ~! T! J3 a8 U
! A: v, e2 t% z( m2 _- return mktime(&stm); 9 u& a/ n0 e# e- t1 s$ W0 s
- }
复制代码 |
实测没毛病,这是HAL库,不懂别乱说
要是把时间戳转本地时间的函数也写出来就更好了。# v1 o. G/ Y9 V, \" N1 X
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); }