帮我写一个时钟bat脚本
时间: 2024-01-30 11:59:59 浏览: 33
@echo off
:start
cls
setlocal enabledelayedexpansion
set /a hour=%time:~0,2%
set /a minute=%time:~3,2%
set /a second=%time:~6,2%
if %hour% geq 12 set ampm=PM
if %hour% lss 12 set ampm=AM
if %hour% equ 0 set hour=12
if %hour% gtr 12 set /a hour-=12
set "hour=0!hour!"
set "minute=0!minute!"
set "second=0!second!"
echo Current Time: %hour:~-2%:%minute:~-2%:%second:~-2% %ampm%
ping -n 2 127.0.0.1 >nul
goto start
Explanation:
The script uses the TIME system variable to get the current time. The hour, minute, and second are extracted from the time string using string manipulation. The AM/PM indicator is determined based on the hour value. The hour value is also converted to 12-hour format if needed.
The setlocal enabledelayedexpansion command is used to enable delayed expansion of variables. This is necessary to avoid issues with leading zeros in the hour, minute, and second values.
The hour, minute, and second values are then padded with leading zeros using the set command and the !variable:~n,m! syntax.
The echo command is used to display the current time in the desired format. The ping command is used to introduce a delay of 1 second between updates. The goto command is used to return to the start of the script and repeat the process.