How to get a UNIVERSAL Windows batch file timestamp - batch-file

I'm having trouble generating a timestamp in a Windows batch file, because I get diferent date formats on different Windows versions.
My machine:
>echo %date%
>Tue 11/17/2009
Friends machine:
>echo %date%
>11/17/2009
I guess there has to be some way of getting the date (11/17/2009) from both strings using for /f. I've been trying and googling and can't find the answer.
Is there another way to get a timestamp without using %date%?

Check out doff.exe. I use this a lot for getting timestamps for naming log files. From its web site:
DOFF prints a formatted date and time, with an optional date offset, (e.g -1 prints yesterday's date, +1 prints tomorrow's date). To view all the options available, execute "doff -h". I typically use this utility for renaming log files so that they include a timestamp, (see the third example below). This code should compile under Unix/Linux, as well as DOS.
Sample commands:
C:\>doff
19991108131135
With no parameters the output is the current date/time in the following format: yyyymmddhhmiss
C:\>doff mm/dd/yyyy
11/08/1999
In the above example a date format specification is given.
#echo off
for /f "tokens=1-3 delims=/ " %%a in ('doff mm/dd/yyyy -1') do (
set mm=%%a
set dd=%%b
set yyyy=%%c)
rename httpd-access.log httpd-access-%yyyy%%mm%%dd%.log
The sample batch file above shows a neat way to rename a log file based on yesterday's date. The "for" command executes doff to print yesterday's date, (the "-1" parameter specifies yesterday), then extracts each component of the date into DOS batch file variables. The "rename" command renames "httpd-access.log" to "httpd-access-[yesterday's date].log"
Also check out Microsoft's now.exe, available in the Windows Server 2003 Resource Kit Tools. One bad thing I found out (the hard way) about it is it sets the ERRORLEVEL to the number of characters printed.
Looks like this:
c:\>now
Thu May 19 14:26:45 2011
Help:
NOW : Display Message with Current Date and Time
Usage : NOW [message to be printed with time-stamp]
NOW displays the current time, followed by its command-line arguments.
NOW is similar to the standard ECHO command, but with a time-stamp.

Use VBScript if you want to get independent date time settings:
thedate = Now
yr = Year(thedate)
mth = Month(thedate)
dy = Day(thedate)
hr = Hour(thedate)
min = Minute(thedate)
sec = Second(thedate)
WScript.Echo yr&mth&dy&hr&min&sec

Unfortunately, it can't be done directly, so you need to resort to hacks like GetDate.cmd.
There are lots of VBScript and small external commandline tools available too, which isn't something I'd take a dependency on unless you're already using something of that nature in your overall system.
Personally, I'd be trying to route around it by using PowerShell which neatly sidesteps the issue completely.

You don't need VBScript. You can do it with something like this:
echo %date:~-10,2%/%date:~-7,2%/%date:~-4,4%
Source

As I have posted in here:
Batch: Timestamp to UNIX Time
What about simple 1-line long C program returning UNIX timestamp? You can retrieve value from %errorlevel% in batch script.
#include <stdio.h>
#include <time.h>
int main(void)
{
return (int) time(NULL);
}
In my test in command prompt it worked:
C:\Users\dabaran\Desktop\cs50\src\C>.\time || echo %errorlevel% && set mytstamp=%errorlevel%
1419609373
C:\Users\dabaran\Desktop\cs50\src\C>echo %mytstamp%
1419609373

Related

Batch File DIR Command to Text File Without Overwrite [duplicate]

This question already has answers here:
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
(30 answers)
Closed 1 year ago.
I'm trying to preserve the dates of files that I'm backing up onto an external drive, in the unlikely event that the dates get messed up for whatever reason (I had a previous experience where I lost date information and had no backup). I'm doing this through a batch file containing the following:
#ECHO OFF
cd E:\PCBackup
dir /s > dirlist.txt
I would simply run this batch file after running my backup using FreeFileSync. Then, if I need to, I can search the txt file for the filename and see its corresponding date.
However, when this batch file runs, if there is a previous dirlist.txt, then it is overwritten with the new dirlist.txt. So, in a scenario where the dates get messed up and I don't yet realize it, if I run this batch file, it will overwrite the previous dirlist.txt with one that has the messed up dates, and I'd lose the date information!
So, what I think I want it to do is, if dirlist.txt already exists, then create a new one, say something like dirlist1.txt, so that I can have several "backups" of the text file that I can manually delete if necessary.
I've seen that one can instead use >> with something like dir /s >> dirlist.txt to append to an existing file instead of overwriting, but I don't want to append if I don't have to, I'd still like to create a new file.
Is there a way to accomplish this? I'm also open to alternative/simpler ways of preserving the dates, if there are any. Please keep in mind that I know little about CMD commands or programming, outside of a computer science course I took years ago. Thank you.
You will be told there are umpteen duplicate ways to do this so in this 22 nd year of the 1st century :-) Windows has no native way of returning a sequential Iso Date the primary answer will be use powershell and for my locale it needs to be called in a suitable format, introducing a delay.
powershell get-date -format "{yyyy-MMM-ddTHH_mm+01Z}"
Note:- colons : are not allowed, and for me 20 seconds later on one machine (but it does get faster with use) and 12-5 seconds later on this one, I get
2021-07-07T21_55+01Z
but actually its now 2021-Jul-07 21:56
I have found that the MakeCab method is faster and reliable but again the format is not pure sequencing and the Jul will NOT appear before Dec in a file list without significant batch file processing.
2021-Dec-31 23:00:00.txt
2021-Jul-08 21:54:20.txt
So in a .cmd I prefer a more instant result thus my clock is set to International dates (You will need to look at your LOCALE clock setting bottom right for your own construction.)
set isodate=%date:~0,10%
instantly returns
isodate=2021-07-07 and I can then use that for filename
#ECHO OFF
cd E:\PCBackup
set "isodate=%date:~0,10%"
dir /s > %isodate%-dirlist.txt
dir returns includes 2021-07-07-dirlist.txt
If you want to run several times in a day use
#ECHO OFF
cd E:\PCBackup
set "isodate=%date:~0,10%"
set "isotime=%time:~0,2%-%time:~3,2%-%time:~6,2%"
dir /s > %isodate%T%isotime%+01Z-dirlist.txt
Amend that any way you wish for your timezone, thus your own clock whatever your date format be it :-
31/2021/12
look at the way I split %time :~ start#base 0 , # of chars %-
one example for an "English" clock date of 31/12/2021 would be simply reverse to
"isodate=%date:~6,4%-%date:~3,2%-%date:~0,2%"
For American %date%=Thu 07/08/2021 use
"isodate=%date:~10,4%-%date:~4,2%-%date:~7,2%"

Windows batch file timestamp to string

I am using the following simple line in my windows batch file to get the current time stamp to a String format so that I can use it later in the batch file to create a folder with same name.
set TIME_STAMP=%DATE:/=-%_%TIME::=-%
I observed that when the time is single digits, say 9:31 AM, I get the String like this:
08-10-2015_ 9.31.52.57
Notice the space between the characters _ and 9.
When the system time is say 10:31 AM, it all works fine, like
08-10-2015_10.31.52.57
Is there something I can do to make the time stamp as
08-10-2015_09.31.52.57
when I have hours in single digits?
just do this
set TIME_STAMP=%DATE:/=-%_%TIME::=-%
echo %TIME_STAMP: =0%
Probably the simpliest approach:
set "TIME_STAMP=%DATE:/=-%_%TIME::=-%"
set "TIME_STAMP=%TIME_STAMP: =0%"
Result:
==> echo "%TIME_STAMP%"
"08.10.2015_07-42-08,18"
==>

Input Error: There is no file extension

If this is a rookie mistake I apologize for wasting your time.
As part of a larger batch file to create a directory with today's date, copy and paste files to be backed up, change permissions and delete files older then X days I've run into a problem. Here's where it happens:
echo var D = new Date() > tmp.js
echo D = (D.getFullYear()*100+D.getMonth()+1)*100+D.getDate() >> tmp.js
echo WScript.Echo( 'set YYYYMMDD='+D ) >> tmp.js
echo #echo off > tmp.bat
cscript //nologo tmp.js >> tmp.bat
call tmp.bat
The command prompt spits back this error:
Input Error: There is no file extension in "C:\Users\name\Desktop\Error:".
So obviously the rest of the batch file fails but the weird thing is this works on one machine on the network but not the other.
Any help is greatly appreciated.
EDIT: there is one more line to that code that is returning the error, my mistake.
After I call tmp.bat:
mkdir "\\network\file\%YYYYMMDD%"
This code, as is, will not generate the indicated error
BUT, if the path to the batch file contains spaces, and the code is something like
cscript //nologo %~dp0\tmp.js
you will get the indicated error as the argument to cscript is incorrectly parsed because the space in the path to the js file. If this is the case (or something similar), quotes in the filename should solve it
cscript //nologo "%~dp0\tmp.js"
Also, the temporary batch file is not needed. Output from cscript can be directly read with the help of for command
set "tmpJS=%~dp0\tmp.js"
>"%tmpJS%" echo with(new Date()){WScript.StdOut.WriteLine(getFullYear()*10000+(getMonth()+1)*100+getDate())};
for /f %%D in ('cscript //nologo //B "%tmpJS%"') do set "YYYYMMDD=%%D"
Wow - that is a very convoluted way to get the current date in a variable.
This is not a direct answer to your question, but I think I can make your life much easier :-)
There really is no need for a temporary batch file. FOR /F could process the output of your temporary JS script directly.
But I have an even easier solution - GetTimeStamp.bat is a hybrid JScript/batch utility that can do nearly any date and time computation on a Windows machine.
The utility is pure script that will run on any modern Windows machine from XP forward - no 3rd party executable required.
Assuming getTimestamp.bat is in your current directory, or better yet, somewhere within your PATH, then the following simple call will define a YYYYMMDD variable containing today's date in YYYYMMDD format:
call getTimeStamp -f {yyyy}{mm}{dd} -r YYYYMMDD
There are a great many options for specifying the base date and time, many options for adding positive or negative offsets to the date and time, many options for formatting the result, and an option to capture the result in a variable. Both input and output can be directly expressed as local time, UTC, or any time zone of your choosing. Full documentation is embedded within the script.
Figured it out:
running cscript on tmp.js led to an error begin put into tmp.bat
call tmp.bat then returned the weird input error because of the error message inside of tmp.bat.
tmp.bat looked like this when editing
Cscript Error: Can't find script engine "JScript" for script "C:\Users\name\Desktop\tmp.js".
That's why calling tmp.bat returned this error message:
Input Error: There is no file extension in "C:\Users\name\Desktop\error:".
The problem ended up being with jscript.dll. It needed to be (re)registered.
regsvr32 %systemroot%\system32\jscript.dll
^Fixed my problem. Thank you all for the help.

Programming in a command file

Need programming help.
Want to add current date to a command
tried this
date /t > stu.txt
call c:\Bin\MKS\sed -e 's/\//-/g' stu.txt | c:\Bin\MKS\cut -c5-14 >stu2.txt
not sure what to do here
then show current date on this command below
c:\Bin\7ZIP\7za.exe a -t7z c:\Bin\Test11-01-2013.7z #c:\Bin\TestList.txt
thanks my programming is very rusty.
Two things that may answer your question (although with you having an odd mix of unix and Windows going there, I'm not sure this will work for you):
1) The output of date can be formatted directly: for example
date +"%m-%d-%Y"
will give
11-01-2013
2) You can get the output of a command inserted into another command by using backticks:
echo the year is `date +"%Y"`
would result in
the year is 2013
You can see how you could use that to insert your date string into a command; or you can put it in an environment variable first (handy if you have more than one place where you want to insert)
set myDate=`date +"%m-%d-%Y"`
echo $myDate
results in
11-01-2013
and you can include that in a file name (or any other command):
cat file_$myDate.txt
will expand to
cat file_11-01-2013.txt
You should be able to take these concepts and map them to what you are trying to do

How to create a batch script to copy newly created folder with the current date

im not good in batch scripting. Hope someone can help me with this.
What my problem is, everyday my program creates a dated folder. I want a automated daily backup scripts that will do the job, I want only the newly created folder with the current date or yesterdays date to copy and rar then send to other directory and the rest of the files and subdirectory remains. Btw, My Program creates a folder name according to current date.
here is the sample
source todays date: february 26 20013
C:\MyApp\20130226 <new folder
\20130225 <old folder
\20130224 <old folder
destination todays date: february 26 20013
D:\Backup\20130226.rar << newly backup according to current date.
Is this possible? Thank you in advance
Date stuff in batch files is notoriously finicky and tricky.
There are basically two ways of going about that:
Use %DATE% and cut it to appropriate pieces, e.g. for me it would look like this:
> echo %DATE%
2013-02-26
> echo %DATE:~0,4%%DATE:~5,2%%DATE:~8,2%
20130226
This has the problem that it's dependent on the date format in your current locale. As you can see, I am using ISO-8601 (the only sane date format imho) which makes this rather easy.
It works well enough for one-off scripts that you use in a clearly defined environment and have no actual requirements of robustness. I tend to avoid that, though.
Use WMI to get the current date:
> wmic os get localdatetime
LocalDateTime
20130226113553.324000+060
You can store that output in a variable with for /f:
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
Since that format is fixed you can safely use substrings to access the individual parts:
echo %MyDate:~0,8%
I'll leave the actual file copying as an exercise to you.

Resources