2

Hi I am running a batch script to get a current date and perform numerical operations on it.

I get the date by using the following command and then do operations on it (Add, Subtract etc).

But If the date returns a value less than 10 (eg. 09, 08) the operation gives an error.

set dd=%date:~7,2%   
set /a dd1=08-1 
Invalid number.  Numeric constants are either decimal (17),hexadecimal (0x11), or octal (021).

Please help

  • 2
    using `date` for getting date is very bad, as it depends on locale. Most of the world use DDMMYYYY, a few others use YYYYMMDD and 1 or 2 countries use MMDDYYYY. Some write date numbers with leading zeros, some don't. Hence `%date:~7,2%` will return vastly different values. The correct way to use is [wmic](http://stackoverflow.com/a/19131662/995714) – phuclv Mar 18 '16 at 08:15
  • I'm working with `%TIME%` - it's just gone 08 minutes past the hour and I've just realized I have this bug too! :/ – yoyo Feb 06 '22 at 04:11

1 Answers1

5

you can remove the zero with a little trick:

set /a dd1=(1%dd: =0%-100)-1

This adds the string "1" to "08" (which is also still a string), resulting in "108". Then subtract "100" (/a treating them as numbers), which results in "8". If in your locale the date has no leading zero but a space instead, %%d: =0% replaces it with a zero

If you need the result with leading zero, just add it again:

set dd1=0%dd1%
set dd1=%dd1:~-2%

This adds the string "0" in front of the string "7" (result from before), resulting in "07" and takes the last two digits from it "07" (in case, the result from before is "24", -> add "0" = "024" -> last two = "24")

edited to work also in locales, where the date has a space instead of a leading zero. (thanks to Lưu Vĩnh Phúc for spotting it)

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • 1
    this doesn't work if the leading zero in day value is not displayed – phuclv Mar 18 '16 at 08:16
  • 1
    @LưuVĩnhPhúc that's why I prefer [another method](http://stackoverflow.com/a/18024049/2152082) to get the date/time in a reliable format, independent of locale settings. But you can handle this: `set /a dd1=(1%dd: =0%-100)-1` (replaces any space with a zero before adding the "1") – Stephan Mar 18 '16 at 09:11
  • I don't think locales that don't write a leading zero put a space there. – phuclv Mar 19 '16 at 03:02
  • I don't know _all_ locales. Do you have an example? . Some (all?) locales definitively use spaces with `%time%`. – Stephan Mar 19 '16 at 06:48