batch command time help

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
wanting2learn
Posts: 2
Joined: 18 Sep 2012 08:15

batch command time help

#1 Post by wanting2learn » 18 Sep 2012 08:18

I need to do the following in a batch file:

Get the current date and time and format it like so:
YYYY-MM-DD:HH:MM:SS
e.g. 2012-08-28:13:00:00

ANd then I also need to subtract a number of seconds from this e.g. 30 seconds

How do I do this in batch file commands.

Thanks

wanting2learn
Posts: 2
Joined: 18 Sep 2012 08:15

Re: batch command time help

#2 Post by wanting2learn » 18 Sep 2012 09:48

So far I have did the following:

Code: Select all

set HH=%TIME:~0,2%
set MM=%TIME:~3,2%
set SS=%TIME:~6,2%
ECHO %HH%:%MM%:%SS%

ECHO %MM%
set /a SECS_IN_MINS=%MM% * 60
ECHO %SECS_IN_MINS%

ECHO %SECS_IN_HOURS%
set /a SECS_IN_HOURS=%HH% * 3600
ECHO %SECS_IN_HOURS%

set /a TOTAL_SECS=%SECS_IN_HOURS% + %SECS_IN_MINS% + %SS%
ECHO %TOTAL_SECS%

set /a NEW_SECS=%TOTAL_SECS% - 30
ECHO %NEW_SECS%


I will then convert this to the new time.

But this will fallover when it changes the midnight boundary.

Is there a reliable way of doing this???

Liviu
Expert
Posts: 470
Joined: 13 Jan 2012 21:24

Re: batch command time help

#3 Post by Liviu » 18 Sep 2012 10:15

wanting2learn wrote:

Code: Select all

set HH=%TIME:~0,2%
set MM=%TIME:~3,2%
set SS=%TIME:~6,2%

This will read %time% 3 different times, and there is the chance that the time may change in between. You should read the time once to an intermediate variable "set T=%TIME%" then use that T variable to parse the hours/minutes/seconds.

wanting2learn wrote:

Code: Select all

set /a SECS_IN_MINS=%MM% * 60

This will fail if MM is 08 or 09 since set/a will take it as an octal number, where digits >7 are invalid. You need to check for and remove the "0" first. This applies to HH and SS as well. See for example :hmsc2xc at http://www.dostips.com/forum/viewtopic.php?f=3&t=3785.

wanting2learn wrote:But this will fallover when it changes the midnight boundary.

Is there a reliable way of doing this???

Code: Select all

if %TOTAL_SECS% geq 30 (set /a NEW_SECS=%TOTAL_SECS% - 30) else (set /a NEW_SECS=%TOTAL_SECS% + 86370)

Liviu

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: batch command time help

#4 Post by foxidrive » 18 Sep 2012 12:01

Here's a method to return the seconds from 01/01/1970.

What is the task that you want to do?


Code: Select all

@echo off
echo Wscript.Echo "set syssec="^&DateDiff("s", "01/01/1970", Now)>temp.vbs
cscript //Nologo temp.vbs>temp.bat
call temp.bat
del temp.bat
del temp.vbs
echo Seconds from 01/01/1970 is %syssec%
pause

Post Reply