0

UPDATE

Solution Found, working code:

@echo off
color f0
title Date Of Birth Generator

:begin

    REM Setting Current Year (Year Cannot Surpass Current Year)
    for /f "tokens=1 delims=-" %%g in ('echo %date%') do (
        set cYear=%%g
    )   

        REM Year
        set /a year=(%RANDOM% %% %cYear%) + 1

            REM Leap Year Check
            set /a mod=%year% %% 4
            if %mod%==0 (
                set jy=1
            ) else (
                set jy=0
            )



    REM Month
    set /a month=(%RANDOM% %% 12) + 1

        REM Define The Maximum Days In Random Month
        if %month%==1 set dm=31
        if %month%==3 set dm=31
        if %month%==5 set dm=31
        if %month%==7 set dm=31
        if %month%==8 set dm=31
        if %month%==10 set dm=31
        if %month%==12 set dm=31

            REM February
            if %month%==2 if %jy%==1 (
                set dm=29
            ) else (
                set dm=28
            )
            set dm=30
            if %month% LSS 10 set month=0%month%

    REM Day
    set /a day=(%RANDOM% %% %dm%) + 1
    if %day% LSS 10 set day=0%day%

    REM Compile Date
    cls
    echo Format: DD/MM/YYYY
    set cDate=%day%/%month%/%year%
    echo %cDate%
    pause>nul
    goto begin

Old Post (original question, original code

This code is supposed to generate a random date taking into consideration the amount of days in a month and if it is a leap year. The problem is, the %random% variable does not seem to be working? When I generate a random month, it always generates 02 on my desktop and 06 on my laptop... I've tried disabling parts of the code and even redesigning the random month generation process. Any ideas would be greatly appreciated!

@echo off
color f0
title Date Of Birth Generator
:begin
for /f "tokens=1 delims=-" %%g in ('echo %date%') do (
set cyear=%%g
)
set /a mod=%cyear% %% 4
if %mod%==0 (
set jy=1
) else (
set jy=0
)

set /a mon=%RANDOM% * (12 - 1 + 1) / 32768 + 1
if %mon%==1 set dm=31
if %mon%==3 set dm=31
if %mon%==5 set dm=31
if %mon%==7 set dm=31
if %mon%==8 set dm=31
if %mon%==10 set dm=31
if %mon%==12 set dm=31
if %mon%==2 if %jy%==1 (
set dm=29
) else (
set dm=28
)
if %mon% LSS 10 set mon=0%mon%
echo %mon%
pause

set /a d=%RANDOM% * (%dm% - 1 + 1) / 32768 + 1

2 Answers2

1

Use this syntax instead to get your random

set /a mon=%RANDOM% %% 12 + 1

Here is a function to get you the last day of a month when you CALL it with the the year and month.

:DaysOfMonth Year Month
setlocal DisableDelayedExpansion
set /a "yy = %~1, mm = 100%~2 %% 100"
set /a "n = 30 + !(((mm & 9) + 6) %% 7) + !(mm ^ 2) * (!(yy %% 4) - !(yy %% 100) + !(yy %% 400) - 2)"
endlocal &set day=%n%
GOTO :EOF

Then you can use the variable day to get your random day of the month.

set /a d=%RANDOM% %% %day% + 1
Squashman
  • 13,649
  • 5
  • 27
  • 36
0

Try this, the Modulus is much better in your scenario:

set /a mon=%RANDOM% %% 12 + 1
Tommy Harris
  • 109
  • 6