Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

In a batch file I need to extract a month, day, year from the date command. So I used the following, which essentially parses the Date command to extract its sub strings into a variable:

set Day=%Date:~3,2%
set Mth=%Date:~0,2%
set Yr=%Date:~6,4%

This is all great, but if I deploy this batch file to a machine with a different regional/country settings, it fails because month, day and year are in different locations.

How can I extract month, day and year regardless of the date format?

share|improve this question
1  
Are you absolutely restricted to Batch? Such a thing is much simpler in VBScript/WSH and/or PowerShell ... –  Adrien Jul 27 '11 at 23:20
    
@Adrien, Yes limited to batch - it's part of the VS2008 post-build step. –  AngryHacker Jul 28 '11 at 0:06

7 Answers 7

up vote 3 down vote accepted

I know it's not exactly what you asked for, but I use the Windows port of the Linux date application from a command inside the batch file and then assign the result to a variable.

I have yet to find a way to get the date reliably using only batch commands.

share|improve this answer

Here is a batch file that addresses exactly this problem:

http://ss64.com/nt/syntax-getdate.html

The trick is that they look what DATE says in which format you need to input the date:

The current date is: Fri 29/07/2011
Enter the new date: (dd-mm-yy)

Based on this information, they parse the extracted date differently.

share|improve this answer
1  
Ah ha, very neat way of finding the locale's date ordering. ss64 does have a nifty community of cmd.exe users. –  Nicholi Jul 28 '11 at 22:06

Have you tried using NET TIME \\%ComputerName% instead of DATE? I think that NET TIME is supposed to provide the data in a consistent format regardless of locale.

share|improve this answer
    
Nope, it doesn't. –  AngryHacker Jul 28 '11 at 0:06
    
Interesting, I just tried it, switching between AU and US formats, and net time always output in m/d/yyyy format. @AngryHacker, with what settings did it not work for you? –  Hydaral Jul 28 '11 at 1:15
1  
I switched French(Belgian) and it gave me 2011-07-27. The US give 07/27/2011 –  AngryHacker Jul 28 '11 at 1:30

While you are right that VS 2008 outputs a batchfile, you can run pretty much any program you want, including Powershell scripts and other programs.

Edit:

Here are some similar questions:

http://stackoverflow.com/questions/1051845/visual-studio-2008-professional-build-process http://stackoverflow.com/questions/3049369/embed-application-compilation-time-stamp

Originally, I was gonna have this moved to SO. . .

share|improve this answer

Use this batch file for YYYY-MM-DD format. It uses the window intrumentation tool that should be present in all recent Windows versions to get a datetime string which is independent of regional settings.

Save to a batch file into the path (eg) c:\windows\rdate.bat then access with a CALL RDATE.BAT to set the rdate variable. Alternately, copy the code into your batch file.

This date format is suitable for filenames and logging. It sorts correctly. The REMed logtime variable adds a date+time variable as YYYY-MM-DD-HHMMSS suitable for use in logging batch file activity to second accuracy.

Adjust the date (and time) formats as you wish. The two numbers in each text selection are the zero-based start character index and the number of characters to copy.

echo off
rem Creates an environment variable rdate as YYYY-MM-DD
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
rem echo %datetime%
set rdate=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%
rem echo %rdate%
rem set logtime=%rdate%-%datetime:~8,6% 
rem echo %logtime%
share|improve this answer

This might be somewhat off topic but here is a .bat file that I wrote for my own scheduled backups and also call from postbuild actions in visual studio. I hope that some will find it useful.

Save the following into a .bat file

--------------------------------------------------
**:: The following is Copyright © 2012 ShopNetNuke Corp.  All rights reserved.
::  and released under the GNU General Public License (GPLv3)**

:: The following section retrieves the current date and time and formats it into the '%var%' variable
:: This format always ensures that the Date and Time are fixed length to avoid the situation of
:: having a value of '12/ 1/2012 rather than '12/01/2012'
echo off
for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
set var=%var: =0%
echo Beginning my valuable Backup Set:  Backup--%var%

:: If you wanted to request the user input a filename prefix, 
:: then we would use something similar to this
:: set /p nameprefix= Enter the file name prefix?
:: Get the Current Date and Time
::for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
:: set var=%var: =0%
:: echo Beginning my valuable Backup Set:  Backup--%var%_%nameprefix%

Pause

echo Starting SQL Server Database Backup Job...
:: The following line initiates the Backup job within SqlServer Agent.
:: Change 'MyBackupNameInSqlAgent' to the name of the job you want executed
:: Change the directory paths to those relevant to your current system installation directories
:: SqlAgent will not return a value if the backup action succeed, 
:: however, in the event an error is encountered, it will be echoed onto the screen
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd.exe" -S SQLSERVERNAME\INSTANCENAME -Q "execute msdb.dbo.sp_start_job @job_name = 'MyBackupNameInSqlAgent'"
:: An error will be returned if the Backup job is not found or has already been triggered by another process

echo Starting My Valuable Source Code Directory Backup...

echo ...backing up files and folders in "C:\Source\MyPreciousProjectDirectory\"...
:: The following line will execute the 7zip command to create a .7z file of the directory named in 'MyPreciousProjectDirectory'
:: and tells it to put the archive in the 'MyPreciousBackupDirectory'.  The compression level will be defined by the 7zip default settings
:: The -p flag tells 7zip to password protect the archive, in this case, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectory\%var%\MyPreciousProject--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\* 

echo Source Code Directory Backups complete.

echo Archiving Database Backups now...
:: The following line will execute the 7zip command to archive the Database backup.
:: The '*' could be replaced by the actual backup name.
:: The '*' indicates all files of type '.bak'
:: The -p flag tells 7zip to password protect the archive, in this case, again, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z  C:\MyPreciousBackupDirectory\%var%\MyPreciousProject-Database-%var%.7z -p%var% -mhe "C:\Program Files\Microsoft SQL Server\MSSQL10.SQLDEV08\MSSQL\Backup\*.bak"

echo Database Backup Archival process complete.

:: If you wanted to place both the previous backups into one single combination archive,
:: you could do something like the following
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var%\MyPreciousProjectBackupSourceAndDatabase--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\* 


echo Now attempting to copy archives to Network Server...
:: The following line will use xcopy to copy the arechives to the server backup directory and place them in a directory named by the DateTime variable %var%
xcopy /S /I /J /Y C:\MyPreciousBackupDirectory\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%
:: Or if the combination above was used then copy that...
xcopy /S /I /J /Y C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%


echo 7z Archive files transferred to MyPreciousBackupServerName successfully
echo  ||
echo \||/
echo  \/
echo ---------------------------------------------------
echo ----- BACKUP SET "%var%" COMPLETE ------
echo ---------------------------------------------------
pause
share|improve this answer
1  
tl;dr , you might add an explanation of what the script does. because it does not come off as a solution right away. It might also be more useful, if you can remove the non pertinent bits of code –  Shekhar Dec 20 '12 at 22:09
    
The whole batch script relies on the %date% and %time% variables, which are locale-aware, and can't really be parsed in a predictable way as the OP asked. –  and31415 Feb 22 at 19:02

Windows XP and later

for /f "tokens=2 delims==" %%G in ('wmic os get localdatetime /value') do set datetime=%%G

set year=%datetime:~0,4%
set month=%datetime:~4,2%
set day=%datetime:~6,2%
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.