I current run the below script to get the current day minus 1 and the current month. It works great for all days and month except for the 8th of every month and August of every year. I have to change the script to setting it manually for August. Does anyone know why and is there a fix.
SET m=%date:~4,2%
SET /A m -= 1
SET m=0%m%
REM ****** SET m=08 this was used because the date was not right ******
REM SET m=08
SET currMon=%date:~4,2%/%date:~10,4%
REM ****** SET PriorMon=12/2017 this was used for Year End because the date was not right ******
REM SET PriorMon=08/2018
SET PriorMon=%m:~-2%/%date:~10,4%
This is a hybrid vb/batch script. It is a proper way to get the date -1 or whatever amount of days you want:
#echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\*%~n0.vbs"
set "yyyy=%result:~0,4%"
set "mm=%result:~4,2%"
set "dd=%result:~6,2%"
set "final=%dd%-%mm%-%yyyy%"
echo %final%
I simply echo the final result here which as far as today's date goes (for me as it is the 7th) should echo 06-09-2018
You can change the format of %final% as you please to suit your date..
Proper date calculatons in pure batch are possible but tedious.
Your approach relies on possibly unknown locale/user settings dependant date format.
From Win7 on Powershell is available as a tool:
On cmd line:
For /f "usebackq" %A in (`powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"`) Do Set Yesterday=%A
In a batch file:
For /f "usebackq" %%A in (`
powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"
`) Do Set Yesterday=%%A
Echo Yesterday=%Yesterday%
Modify the format string to your liking:
dd = day 2 places
MM = month 2 places
yyyy = year 4 places
Other characters have to be escaped with a backslash.
Related
I'm looking to include a script in my batch file that copies file "X" from a directory, say, "[...]\2017\08 August\08.28" (previous weekday-1) to a directory: "2017\08 August\08.29" (previous weekday).
I currently do have two batch files which perform number of things for yesterday or 3 days ago (executing on Mondays), but I'd like to include that one line as well and preferably merge that into one file that automatically detects if the previous day is weekday, or not. What I do have now, simplified, is:
#echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
if %MM%==08 (
set "mon=August"
)
copy "\2017\08 August\08.28\X" "\%YYYY%\%MM% %mon%\%MM%.%DD%"
How could I make that automatically adjustable?
The question wanders around a bit. The key seems to be that you want to know if yesterday was a weekday. This should help:
#echo off
set IYW_CURDAT=%DATE%
set IYW_CURDOW=%IYW_CURDAT:~0,3%
set IYW_YESWDY=TRUE
if /I "%IYW_CURDOW%" EQU "Sun" set IYW_YESWDY=FALSE
if /I "%IYW_CURDOW%" EQU "Mon" set IYW_YESWDY=FALSE
if [%IYW_YESWDY%] == [TRUE] echo Yesterday was a weekday
if [%IYW_YESWDY%] == [FALSE] echo Yesterday was NOT a weekday
set IYW_CURDAT=
set IYW_CURDOW=
set IYW_YESWDY=
Is there a way to get the first and the last day of the previous week into two variables on the windows command line?
The date format I'd like to use is YYYY-MM-DD.
If you can use vbscript, you can try the following:
Create the file vbdate.vbs:
function YMD(d)
YMD = Year(d) & _
"-" & Right("00" & Month(d),2) & _
"-" & Right("00" & Day(d),2)
end function
set oArgs=WScript.Arguments
' Assuming first day of the week is Monday:
WScript.echo YMD(DateAdd("d", -((Weekday(Now()) + 7 - 2) Mod 7) + oArgs(0), Now()))
If you want Sunday to be first day of the week, replace the last line by:
WScript.echo YMD(DateAdd("d", -((Weekday(Now()) + 7 - 1) Mod 7) + oArgs(0), Now()))
This vbscript takes one argument, beware its sole purpose is to perform the date calculation you asked for:
6 will give you the last day of the current week
0 will give you the first day of the current week
-1 will give you the last day of the previous week
-7 will give you the first day of the previous week
To put requested values into two variables you can do the following:
#echo off
FOR /F "usebackq tokens=*" %%r in (`CSCRIPT //Nologo "vbdate.vbs" -7`) DO SET RESULT1=%%r
FOR /F "usebackq tokens=*" %%s in (`CSCRIPT //Nologo "vbdate.vbs" -1`) DO SET RESULT2=%%s
REM First day of previous week
ECHO %RESULT1%
REM Last day of previous week
ECHO %RESULT2%
I'm not sure how you define your week, but I will assume the week starts with Sunday.
Doing date/time computations in batch is a pain. But the problem can be solved easily if you use my getTimestamp.bat utility - a hybrid JScript/batch script that can be used to perform nearly any date/time computation and formatting task. The utility is pure script that runs natively on any Windows machine from XP onward.
#echo off
setlocal
call getTimestamp /f "{w}" /r dayOfWeekNum
call getTimestamp /od "-%dayOfWeekNum%-7" /f "{yyyy}-{mm}-{dd}" /r beginDate
call getTimestamp /od "-%dayOfWeekNum%-1" /f "{yyyy}-{mm}-{dd}" /r endDate
echo Last week begin date = %beginDate%
echo Last week end date = %endDate%
EDIT
The above can easily be generalized to support any day as the start of the week. Also, the script could give the wrong result if it is run a split second before midnight on the night it transitions from one week to the next. I solved that below by getting the current date only once, and then performing all computations relative to that date.
The script below assigns Monday as the start of the week.
#echo off
setlocal
set "weekStart=1" %= 0=Sunday, 1=Monday, 6=Saturday =%
call getTimestamp /f "{ums}" /r today
call getTimestamp /d %today% /f "{w}" /r dayOfWeekNum
set /a "dayOfWeekNum=(7+dayOfWeekNum-weekStart)%%7"
call getTimestamp /d %today% /od "-%dayOfWeekNum%-7" /f "{wkd} {yyyy}-{mm}-{dd}" /r beginDate
call getTimestamp /d %today% /od "-%dayOfWeekNum%-1" /f "{wkd} {yyyy}-{mm}-{dd}" /r endDate
echo Last week begin date = %beginDate%
echo Last week end date = %endDate%
I am using this to get the date modified of a file:
#echo off
FOR %%? IN ("C:\some.exe") DO (
ECHO Last-Modified Date : %%~t?
)
The above returns something like: Last-Modified Date : 26/03/2013 14:43.
How can I take the date part from the above and compare it against another file which's name contains a date ie: 23-Sep-13.exe?
I need to be able to perform some code in the batch file if the file that contains the date in its name is later than the file modified version ie install the update.
#ECHO OFF
SETLOCAL
:: No doubt for international use, this could be retrieved from the registry
SET monthnames=Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
:: get last modified date of target file - your format as specified
:: (I used THIS BATCH FILE)
FOR %%i IN ("%~f0") DO SET target=%%~ti
:: parse the target date
FOR /f "tokens=1-3delims=/ " %%i IN ("%target%") DO SET targetf=%%k%%j%%i
::
:: parse name from 'other file'
SET other=23-Sep-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
:: #ECHO on
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
::
:: parse name from 'another other file'
SET other=23-Jan-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
Code takes date of (this batch) as the target (your 'C:\some.exe'- change to suit.
test then applied to two different filename-is-date+ext format filenames to test.
Can be easily adjusted if comparisons to 20th-Century date is required... :)
I currently have the following code in a batch file Backup.bat on my desktop. it is used to back up an excel spreadsheet file each day and rename it by appending the current date and time. File.xlsx is copied and pasted to a new folder as File Sun-06-24-2012 23.21.46PM.xlsx
Currently the date and time is appended as Sun-06-24-2012 23.21.46PM.xlsx but i would like to have it append as Sun-06-24-2012 11.21.46PM.xlsx using the 12 hour clock rather than 24 hour clock format.
Below is the code i am currently using in Windows XP Professional. Would anyone know how to have the time appended in 12 hour clock format rather than 24 hour clock format as it is currently in the code below.
#For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do #(
Set DayW=%%A
Set Day=%%B
Set Month=%%C
Set Year=%%D
Set All=%%A-%%B-%%C-%%D
)
#For /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do #(
Set Hour=%%A
Set Min=%%B
Set Sec=%%C
Set Allm=%%A.%%B.%%C
)
#For /F "tokens=3 delims=: " %%A in ('time /t ') do #(
Set AMPM=%%A
)
copy "C:\Temp\File.xlsx" "C:\Temp\DailyBackup\File %All% %Allm%%AMPM%.xlsx"
I agree with Joey's comment, I think you are better off with 24 hour format.
Also, your method for getting the date and time will break as soon as the code is transferred to another machine that uses a different date and/or time configuration.
But, here goes anyway...
You should get the entire time string from a single %TIME% expansion. Otherwise you run the risk of getting the hour:min:sec before midnight and the AMPM after midnight.
Put #ECHO OFF at the top, then you don't need to sprinkle # throughout your code.
#echo off
For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do (
Set DayW=%%A
Set Day=%%B
Set Month=%%C
Set Year=%%D
Set All=%%A-%%B-%%C-%%D
)
For /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do (
set /a "Hour=100%%A%%100"
set Min=%%B
set Sec=%%C
)
if %Hour% geq 12 (
set AMPM=PM
set /a "Hour-=12"
) else set "AMPM=AM"
if %Hour% equ 0 set "Hour=12"
if %Hour% lss 10 set "Hour=0%Hour%"
set "Allm=%Hour%.%Min%.%Sec%%AMPM%"
echo on
copy "C:\Temp\File.xlsx" "C:\Temp\DailyBackup\File %All% %Allm%.xlsx"
Time /t is giving you the time in 24-hour format, presumably because that's the default for your computer's locale.
As time /t doesn't appear to offer any formatting options, probably the easiest thing to do is add an extra section to your batch file to convert the 24-hour clock to 12-hour.
Somewhere under Set Hour=%%A you just need to:
Subtract 12 from the hour if it's more than 12
Change '00' into '12'
For example:
If %Hour% gtr 12 (
Set /a Hour=%Hour%-12
)
If %Hour% == 00 (
Set Hour=12
)
The /a switch on Set tells it that the value to the right of the equals sign is a numerical expression to be evaluated.
This will leave you with no leading zero on the hour if it comes out from 1 to 9. You could get around this with another if statement to add a leading zero back in, or there might be a more elegant approach!
hello i got a batch file, something like this:
if %day%==monday, tuesday, wednesday, thursday, friday (
goto yes
) else (
goto no
)
Now i know the first line won't work.
What i actually want to happen:
It automatticly checks which day it is. If it is Monday to Friday, it has to go to 'yes', otherwise (saturday/sunday) to 'no'.
How to do this?
Here is an example bat file that will do this sort of thing I am sure you can think of other ways to use this sample code. For instance anytime you need an "in" list. The tricky bit is the %date:~0,3% this says expand the %date% environment variable and starting at position 0 the beginning of the string return the next 3 characters. You can learn more about this from the "set /?" command.
example: IsWeekDay.bat
#echo off
setlocal
for %%i in (Mon,Tue,Wed,Thu,Fri) do (
if "%date:~0,3%"=="%%i" goto YES
)
:NO
echo No
goto EOF
:YES
echo Yes
:EOF
endlocal
I ran across this online. Tested, and it works. Returns the day as an integer, which you can still work with.
#For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do #(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
#echo DAY = %Day%
#echo Month = %Month%
#echo Year = %Year%
As Jay has mentioned, using date /t will only work on locales where this command outputs the day of week along with the date, and won't work on other locales (e.g. Russian). If you don't mind mixing your batch files with some VBScript, here's a solution that should work on all locales.
The trick is this tiny VBScript script that outputs the day of the week as a number (1 = Sunday, 2 = Monday, ... 7 = Saturday):
WScript.Echo DatePart("w", Date)
You can run this script from your batch file, read its output and apply your logic:
for /f %%d in ('cscript dayofweek.vbs //nologo') do (
if %%d==7 goto no :: Saturday
if %%d==1 goto no :: Sunday
)
goto yes
IF %day% == monday GOTO YES
IF %day% == tuesday GOTO YES
IF %day% == wednesday GOTO YES
IF %day% == thursday GOTO YES
IF %day% == friday GOTO YES
GOTO NO
I don't have the batch fu to answer the question as asked, but, assuming this is a Windows batch file, consider executing the script using the task scheduler, which will let you set the kind of schedule you're asking for.
Here is a batch file that extracts day-of-week, day, month and year in an almost locale-neutral way.
The only locale specific thing is the spelling of the day-of-week, the rest is locale neutral.
So in English, it will return Thu for Thursday, but in Dutch that will be do (for donderdag).
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen#pluimers.com for Dutch locale
:: 20110303 - adapted by jeroen#pluimers.com for day-of-week
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: Also, in Dutch, there is a difference between %date% and date/t: the former will not include
:: the day-of-the-week, but the latter will.
:: That means the if "%date%A" LSS "A" trick does not work with %date%, we need a loop
:: to check if the day-of-the-week needs us to take tokens 2-4 in stead of 1-3:
:: if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
:: for /f "tokens=1" %%t in ('date/t') do (...)
::
:: Another difference between Dutch and English is that the Dutch date/t will prepend the day of the week in a lower case 2-letter form.
:: So the LSS "A" trick needs to be replaced with an LSS "a" trick
:: if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
:: if "%%ta" LSS "a" (set toks=1-3) else (set toks=2-4)
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
#ECHO off
set v_day_of_week=
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1" %%t in ('date/t') do (
set v_day_of_week=%%t
if "%%ta" LSS "a" (set toks=1-3) else (set toks=2-4)
)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET day_of_week=%v_day_of_week% & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
echo day of week=%day_of_week%
:EOF
Have fun with it!
--jeroen
From this answer, we have
wmic path win32_localtime get dayofweek
Expanding on this based on suggestions in this thread, we can set a dayofweek variable as follows:
#echo off
REM Unset dayofweek in case set in a previous execution of this batch file
set dayofweek=
REM Get dayofweek into a variable. Locale-specific: 0 is either Sunday or Monday.
for /F "skip=1 tokens=*" %%a in ('wmic path win32_localtime get dayofweek') do if not defined dayofweek set dayofweek=%%a
echo %dayofweek%
Note that 0 can be Sunday or Monday depending your locale.