5

I have been trying to find a way of getting a windows batch file to display the current UTC time when run. So in other words get the current amount of milliseconds since it was initiated in 1970.

Does anyone know how to do this.

dgw
  • 13,418
  • 11
  • 56
  • 54
AlanF
  • 1,591
  • 3
  • 14
  • 20
  • 8
    1970 has nothing to do with UTC. 1970-01-01 is the Unix time epoch and Unix time uses UTC, but apart from that the two are completely unrelated. – Joey Mar 26 '12 at 12:28

3 Answers3

12

Using WMI:

for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x

This will set the variables Day, DayofWeek, Hour, Minute, Month, Quarter, Second, WeekInMonth and Year which you can use, then.

You won't get a time with Unix epoch from Windows easily, though. If you have PowerShell you can use

[long]((date).touniversaltime()-[datetime]'1970-01-01').totalmilliseconds

which you can call from a batchfile via

powershell "..."

But in that case you could write your batch file in a real language anyway.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

Alternative:

REM get UTC times:
for /f %%a in ('wmic Path Win32_UTCTime get Year^,Month^,Day^,Hour^,Minute^,Second /Format:List ^| findstr "="') do (set %%a)
Set Second=0%Second%
Set Second=%Second:~-2%
Set Minute=0%Minute%
Set Minute=%Minute:~-2%
Set Hour=0%Hour%
Set Hour=%Hour:~-2%
Set Day=0%Day%
Set Day=%Day:~-2%
Set Month=0%Month%
Set Month=%Month:~-2%
set UTCTIME=%Hour%:%Minute%:%Second%
set UTCDATE=%Year%%Month%%Day%
BJK
  • 31
  • 1
0
wmic TIMEZONE get * /value

Sample Output

Bias=-480
Caption=(UTC-08:00) Pacific Time (US & Canada)
DaylightBias=-60
DaylightDay=2
DaylightDayOfWeek=0
DaylightHour=2
DaylightMillisecond=0
DaylightMinute=0
DaylightMonth=3
DaylightName=Pacific Daylight Time
DaylightSecond=0
DaylightYear=0
Description=(UTC-08:00) Pacific Time (US & Canada)
SettingID=
StandardBias=0
StandardDay=1
StandardDayOfWeek=0
StandardHour=2
StandardMillisecond=0
StandardMinute=0
StandardMonth=11
StandardName=Pacific Standard Time
StandardSecond=0
StandardYear=0

In this example, I want UTC information, so that when I output to log, I can insert UTC information:

wmic TIMEZONE get * /value | FIND /I "Description"

Now I want to parse the string:

(Note in .cmd script/program, use %%P, %P only for console)

FOR /F "tokens=2 delims==" %P IN ('wmic TIMEZONE get * /value ^| FIND /I "Description"') DO Echo %P> var_UTC.txt

Now I want to set a variable that contains UTC

SET /P $SYSTEM_UTC= < var_UTC.txt

Now I want to use variable when writing out to log

(Note how having it in a variable allows for control over text)

echo 2020-12-15 [INFO] %$SYSTEM_UTC% > program.log

You can check out my Github repo's for some complex programs