q; Date to string in a batch file

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

echo %DATE:~10,4%%DATE:~4,2%
this give 200609

how can I get previous month. So if current month is 09, I need 200608. In
Jan 2007, I need to get 200612.
 
JIM.H. said:
echo %DATE:~10,4%%DATE:~4,2%
this give 200609

how can I get previous month. So if current month is 09, I need 200608. In
Jan 2007, I need to get 200612.

@echo off
set /a month=%date:~4,2% -1
set year=%date:~10,4%
if %month%==0 (set month=12 & set /a year=%year%-1)
 
Thanks for the reply. I get error in teh followin line

set /a month=%date:~4,2% -1
Invalid number. Numeric constants are either decimal (17),
hexadecimal (0x11), or octal (021).
 
You have to play around with your variables. My %date%
format is different from yours, hence I cannot tell you what's
wrong. With your current knowledge of batch files it should
be easy for you to get this right.
 
Thanks for the reply. Here is what I get when I run it.
C:\Tmp>echo %date:~4,2%
09

It seems return value is considered as string not a number. How can I
resolve this issue, any idea?
 
I see. The Command Prompt does not like "09" because of
the leading "0" - it treats it as octal. This should work:

@echo off
if %date:~4,1%==0 (set month=%date:~5,1%) else (set month=%date:~4,2%)
set year=%date:~10,4%
set /a month=%month% -1
if %month%==0 (set month=12 & set /a year=%year%-1)
 
Back
Top