The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,230 other followers

batch-file: Getting current yyyyMMdd date into an environment variable.

Posted by jpluimers on 2010/08/04

This seems to be a recurring question on a lot of forums:

How to get the current date as yyyyMMdd into environment variable datestring in a regional independent way?

A lot of solutions are using construct around the %date% environment variable similar to this:

for /f "usebackq tokens=1,2,3,4 delims=- " %%i in (`echo %date%`) do (
set datestring=%%l%%k%%j
echo %%i
echo %%j
echo %%k
echo %%l
echo %datestring%

There are two things wrong with this kind of solution:

  1. It depends on the order of fields inside the %date% environment variable
  2. It depends on the delimiter inside the %date% environment variable (specified by delims in the above example)

(note: the %date% environment variable has the same format as the date command).

For sytems having Powershell installed, this is a possible solution:

for /f "usebackq" %%i IN (`Powershell Get-Date -f "yyyyMMdd"`) DO (
set datestring=%%i
echo %%i
echo %%j
echo %%k
echo %%l
echo %datestring%

This uses the for command trick to parse the output of another command.

You might think there are easier ways of sharing environment variables between Powershell and cmd batch-files, but there seem to be none.
In fact the other way around involves an even more complex way involving a temporary file.

If you do know about an easier way to get environment variables from PowerShell to cmd batch-files, please do comment below :-)


PS: I’m fully aware that if you start using PowerShell, it is a good thing to start moving your cmd batch-files to PowerShell as well.
Two things: time, and a lot of cmd batch-file depending on quirks that are difficult to get rid of.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: