Kirill
Kirill

Reputation: 1538

How to add time in 12-hours format to filename using Windows command line?

I need to have filename with hours in 12-hours format - from 1 to 12 (with am or pm optional) like below:

myfile_2pm.txt

I wrote script but it works only for 24-hours format and crashes if it has "1-digit" hour because colon:

Hello > myfile_%time:~-0,2%.txt

Upvotes: 1

Views: 4949

Answers (4)

dbenham
dbenham

Reputation: 130819

MC ND has a good simple solution using pure batch. But it is very specific to your exact requirements.

Working with date and time on Windows batch is painful, especially if you want a solution that works with any locale, given that the format of %DATE% and %TIME% varies between machines.

I have written a handy hybrid JScript/batch utility called getTimestamp.bat that performs date and time computations and formatting. It can handle nearly any date/time computation or formatting task you are likely to have. The utility is pure script that runs natively on any modern Windows machine from XP onward. Full documentation is embedded within the script.

Assuming getTimestamp.bat is in your current directory, or better yet, somewhere within your PATH, then the following will store the current hour using your format in the hr variable:

call getTimestamp -f _{h}{pm} -r hr

Upvotes: 1

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions

    call :get12h hour
    echo %hour%

    echo This is a test > myfile_%hour%.txt

    exit /b

:get12h outputVar
    setlocal enableextensions
    for /f "tokens=1 delims=: " %%a in ("%time: =0%") do set /a "h=1%%a-100"
    if %h% gtr 11 ( 
        set "td=pm" & if %h% gtr 12 set /a "h-=12"
    ) else ( 
        set "td=am" & if %h% equ 0 set "h=12"
    )
    endlocal & set "%~1=%h%%td%" & exit /b

This uses a subroutine that when called returns the current time in 12h format in the variable used as argument. Return value will be in the range

12am , 1am , .... 12pm, 1pm, .... 11pm

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77065

Do

set hr=%time:~0,2%
set hr=%hr: =0%

Then use %hr% inside whatever string you are formatting to always get a 2-digit hour.

Upvotes: 1

Baljeetsingh Sucharia
Baljeetsingh Sucharia

Reputation: 2079

don't know about am / pm but for single digit try putting " ", i.e. enclose the command with double quotes should work for you.

Upvotes: 1

Related Questions