Sfoglia il codice sorgente

fix(calendar): leap year time to unix timestamp

JimMoen 2 anni fa
parent
commit
0a33f9d027

+ 22 - 0
apps/emqx_rule_engine/test/emqx_rule_funcs_SUITE.erl

@@ -1048,6 +1048,7 @@ t_parse_date_errors(_) ->
     ),
 
     %% Compatibility test
+    %% UTC+0
     UnixTs = 1653561612,
     ?assertEqual(
         UnixTs,
@@ -1062,6 +1063,27 @@ t_parse_date_errors(_) ->
     ?assertEqual(
         UnixTs,
         emqx_rule_funcs:date_to_unix_ts(second, <<"%Y-%m-%d %H:%M:%S">>, <<"2022-05-26 10-40-12">>)
+    ),
+
+    %% UTC+0
+    UnixTsLeap0 = 1582986700,
+    ?assertEqual(
+        UnixTsLeap0,
+        emqx_rule_funcs:date_to_unix_ts(second, <<"%Y-%m-%d %H:%M:%S">>, <<"2020-02-29 14:31:40">>)
+    ),
+
+    %% UTC+0
+    UnixTsLeap1 = 1709297071,
+    ?assertEqual(
+        UnixTsLeap1,
+        emqx_rule_funcs:date_to_unix_ts(second, <<"%Y-%m-%d %H:%M:%S">>, <<"2024-03-01 12:44:31">>)
+    ),
+
+    %% UTC+0
+    UnixTsLeap2 = 1709535387,
+    ?assertEqual(
+        UnixTsLeap2,
+        emqx_rule_funcs:date_to_unix_ts(second, <<"%Y-%m-%d %H:%M:%S">>, <<"2024-03-04 06:56:27">>)
     ).
 
 %%------------------------------------------------------------------------------

+ 10 - 1
apps/emqx_utils/src/emqx_utils_calendar.erl

@@ -478,7 +478,8 @@ do_parse(DateStr, Unit, Formatter) ->
             (year, V, Res) ->
                 Res + dy(V) * ?SECONDS_PER_DAY * Precise - (?SECONDS_FROM_0_TO_1970 * Precise);
             (month, V, Res) ->
-                Res + dm(V) * ?SECONDS_PER_DAY * Precise;
+                Dm = dym(maps:get(year, DateInfo, 0), V),
+                Res + Dm * ?SECONDS_PER_DAY * Precise;
             (day, V, Res) ->
                 Res + (V * ?SECONDS_PER_DAY * Precise);
             (hour, V, Res) ->
@@ -563,6 +564,14 @@ date_size(timezone) -> 5;
 date_size(timezone1) -> 6;
 date_size(timezone2) -> 9.
 
+dym(Y, M) ->
+    case is_leap_year(Y) of
+        true when M > 2 ->
+            dm(M) + 1;
+        _ ->
+            dm(M)
+    end.
+
 dm(1) -> 0;
 dm(2) -> 31;
 dm(3) -> 59;

+ 1 - 0
changes/ce/fix-12632.en.md

@@ -0,0 +1 @@
+Fix incorrect results from rule SQL built-in function `date_to_unix_ts` after March on leap years.