Date and Time scripting

< All Topics

The function to obtain the date and time on RouterOS is very simple

:local date [/system clock get date]
:local time [/system clock get time]

Bad news, the variable $date contains the value “Dec/25/2018” which is not very adapted to scripting operations. Then if you want to get a more adapted format, such as 2018-12-25, you have to manipulate the content of the variable :

:local date [/system clock get date] 
:local day [ :pick $date 4 6 ]
:local month [ :pick $date 0 3 ]
:local year [ :pick $date 7 11 ]

Now you have the good values in the three variables. But $month gives you “dec”, not “12”. You need to convert this element

:local date [/system clock get date];
:local months {"jan"="01";"feb"="02";"mar"="03";"apr"="04";"may"="05";"jun"="06";"jul"="07";"aug"="08";"sep"="09";"oct"=10;"nov"=11;"dec"=12};
:local day [:tonum [:pick $date 4 6]];:local year [:tonum [:pick $date 7 11]];:local month [:pick $date 0 3];:local mm (:$months->$month);
:local newdate "$year-$mm-$day";

And that’s it, the newdate variable now contains “2018-12-25”.

The Mikrotik forums provides many examples of date manipulations. The following example provided by BlackVS (here) gives a good overview of some advances scripting possibilites :

###func_shiftDate - add days to date
#Input: date, days
#date - "jan/1/2017"
#days - number
#correct only for years >1918
#uncomment for testing
#:local date "jan/01/2100"
#:local days 2560
#:put "$date + $days"

:local mdays {31;28;31;30;31;30;31;31;30;31;30;31}
:local months {"jan"=1;"feb"=2;"mar"=3;"apr"=4;"may"=5;"jun"=6;"jul"=7;"aug"=8;"sep"=9;"oct"=10;"nov"=11;"dec"=12}
:local monthr {"jan";"feb";"mar";"apr";"may";"jun";"jul";"aug";"sep";"oct";"nov";"dec"}
:local dd [:tonum [:pick $date 4 6]]
:local yy [:tonum [:pick $date 7 11]]
:local month [:pick $date 0 3]
:local mm (:$months->$month)
:set dd ($dd+$days)
:local dm [:pick $mdays ($mm-1)]
:if ($mm=2 && (($yy&3=0 && ($yy/100100 != $yy)) || $yy/400400=$yy) ) do={ :set dm 29 }
:while ($dd>$dm) do={
:set dd ($dd-$dm)
:set mm ($mm+1)
:if ($mm>12) do={
:set mm 1
:set yy ($yy+1)
:set dm [:pick $mdays ($mm-1)]
:if ($mm=2 && (($yy&3=0 && ($yy/100100 != $yy)) || $yy/400400=$yy) ) do={ :set dm 29 }
:local res "$[:pick $monthr ($mm-1)]/"
:if ($dd<10) do={ :set res ($res."0") }
:set $res "$res$dd/$yy"
:return $res

With this function you have a function that can be executed in another script :

:local shiftDate [:parse [/system script get func_shiftDate source]]

:put [$shiftDate date="jan/01/2017" days=256]

You should get “sep/14/2017”

Previous Conditional scripts
Next DNS scripting
Table of Contents