How to format time?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
STEVEC5088
Posts: 1
Joined: 24 Feb 2009 02:36

How to format time?

#1 Post by STEVEC5088 » 24 Feb 2009 02:47

I am trying to generate time in 12-hour time, format HH:MI:SS PM, but don't know if there is a way to do it in 1 step. (It will be used to annotate a web cam picture.)

I have come up with the two steps below:

Code: Select all

@echo %%time%% = %time%
@FOR /f "tokens=1-2" %%i in ('time /t') do @(
SET HrMin=%%i
SET ampm=%%j
)
:: Get seconds from %time%
@FOR /f "tokens=1-4 delims=:." %%e in ("%time%") do @(
SET SS=%%g
)
@echo Time   = %HrMin%:%ss% %ampm%

which returns:

Code: Select all

%time% =  0:46:32.36
Time   = 12:46:32 AM

But note that I had to pull ss from %time%, while the main part came from 'time /t'

Is there a way to use the first half of my code AND include seconds?

...or is there a better way?

I am really green with DOS batch commands, so thank you for any and all help.

RElliott63
Expert
Posts: 80
Joined: 04 Feb 2009 10:03

#2 Post by RElliott63 » 24 Feb 2009 12:33

I have this snippet inside a "GetDate" script that I call all the time.

Put this into a "GetTime" script and call it. Then do a "Set Time." from a command prompt and use the var that you need in your code.

as in:

...
Call GetTime
Set Log=LogFile-%time.HHMMSS%.csv

...


-R

Code: Select all

:: 
:: Get the TIME details
::
Set "WT=%Time%"
Set time.HH=%WT:~0,2%
Set time.MM=%WT:~3,2%
Set time.SS=%WT:~6,2%

::============================================================================::
Set time.AMPM=PM
If /I %time.HH% LSS 10 (
   Set time.HH=0%time.HH:~1,1%
)
If /I %time.HH% LSS 12 (
   Set time.AMPM=AM
   Set time.HH12=%time.HH%
)  Else (
   Set /a time.HH12=%time.HH%-12
)
If /I %time.MM% LSS 10 (
   Set time.MM=0%time.MM:~1,1%
)
If /I %time.SS% LSS 10 (
   Set time.SS=0%time.SS:~1,1%
)
If /I %time.HH12% lss 10 (
   Set time.HH12=0%time.HH12%
)
Set time.HHMMSS=%time.HH%%time.MM%%time.SS%
Set time.HHMMSS2=%time.HH12%%time.MM%%time.SS%%time.AMPM%
Set time.USA=%time.HH%.%time.MM%.%time.SS%
Set time.USA2=%time.HH12%.%time.MM%.%time.SS% %time.AMPM%

Post Reply