Parsing Dates in Batch Files & Regional Settings / Locale

  • Scripting
  • Published Feb 2, 2011 Updated Sep 6, 2011

Determining day, month and year on the command line is surprisingly difficult if the solution is to work across locales, i.e. on international systems with different regional settings. Although we can use the variables %DATE% and %TIME% their contents is specific to the locale. If set to German, the date is displayed in the format dd.MM.yyyy, if set to English (United States), the date format is M/d/yyyy.

Searching the web I have found several solutions to this, the most elegant relying on WMI to return date and time independent of the locale. My script below is a modified version of of Rob van der Woude’s script SortDate.bat.

In the script, the WMI command-line tool WMIC is used to get year, month, day, hour, minute and second individually. Out of those individual values the formatted date and time strings are constructed. Unfortunately, WMI does not return the milliseconds, so that we are limited to a resolution of seconds.

The output from the script looks like this:

D:\>FormattedDateTime.cmd
FormattedDate=2011-02-02
FormattedTime=17:39:02

Of course, the actual formatting can be changed easily.

And here is the script FormattedDateTime.cmd:

@echo off

::
:: Get date/time independent of system locale and regional settings
:: By Helge Klein
:: Based on code by Rob van der Woude (http://www.robvanderwoude.com/files/sortdate5_xp.txt)
::

setlocal ENABLEDELAYEDEXPANSION

:: Use WMIC to retrieve date and time
for /f "skip=1 tokens=1-6" %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
	if not "%%~f"=="" (
		set /A FormattedDate=10000 * %%f + 100 * %%d + %%a
		set FormattedDate=!FormattedDate:~0,4!-!FormattedDate:~4,2!-!FormattedDate:~6,2!
		
		set /A FormattedTime=10000 * %%b + 100 * %%c + %%e
		set FormattedTime=0000000!FormattedTime!
		set FormattedTime=!FormattedTime:~-6,2!:!FormattedTime:~-4,2!:!FormattedTime:~-2,2!
	)
)

:: Display the results
set formatted

endlocal

Comments

Latest Posts

Scripted WordPress to Hugo Migration

Scripted WordPress to Hugo Migration
After having published in WordPress for almost 20 years, it was time for a change. This site is now rendered by Hugo, a static website generator built for Markdown content hosted in a Git repository. The migration from WordPress (HTML) to Hugo (Markdown) was far from trivial. Since I couldn’t find any tool for the job, I developed my own set of migration scripts that fully automate the migration process. You can find them on GitHub along with extensive documentation.
Website