You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Windows CMD如何创建带AM/PM的时间变量并组合指定日期格式

Solution for CMD Variable in MON-DAY-YEAR_TIME-AM/PM Format

Got it, let's walk through exactly how to build this CMD variable that matches your MON-DAY-YEAR_TIME-AM/PM format—no detours into PowerShell, since you specified sticking strictly to CMD. Here's a robust, locale-friendly solution that avoids relying on system-specific date formats:

Full Batch Script Code

@echo off
setlocal enabledelayedexpansion

:: Step 1: Capture TIME /T output and format it to TIME-AM/PM
for /f "delims=" %%t in ('time /t') do set "raw_time=%%t"
:: Replace colon with hyphen, then replace space with hyphen
set "formatted_time=!raw_time::=-!"
set "formatted_time=!formatted_time: =-!"

:: Step 2: Get standardized date components using WMIC (avoids locale issues)
for /f "skip=1 tokens=2-4 delims=." %%d in ('wmic path win32_localtime get day^,month^,year /format:list') do (
    set "day=0%%d"
    set "month=0%%e"
    set "year=%%f"
)
:: Pad day/month with leading zero (take last 2 characters to handle single-digit values)
set "day=!day:~-2!"
set "month=!month:~-2!"

:: Step 3: Map numeric month to 3-letter abbreviation
set "month_01=JAN"
set "month_02=FEB"
set "month_03=MAR"
set "month_04=APR"
set "month_05=MAY"
set "month_06=JUN"
set "month_07=JUL"
set "month_08=AUG"
set "month_09=SEP"
set "month_10=OCT"
set "month_11=NOV"
set "month_12=DEC"
call set "mon=%%month_!month!%%"

:: Step 4: Build final formatted datetime variable
set "final_datetime=!mon!-!day!-!year!_!formatted_time!"

:: Verify the result (remove this line if not needed)
echo Final formatted datetime: !final_datetime!

endlocal & set "final_datetime=%final_datetime%"

Key Details & Explanations

  • Time Handling: We capture the exact output of TIME /T (e.g., 10:54 AM) and transform it by replacing the colon and space with hyphens, resulting in 10-54-AM.
  • Date Reliability: Instead of using %date% (which varies by system locale), we use wmic to fetch date components in a consistent format. This ensures the script works regardless of regional date settings.
  • Month Abbreviations: We map numeric months (01-12) to their 3-letter uppercase abbreviations to match your MON requirement.
  • Variable Persistence: The endlocal & set line ensures the final_datetime variable remains available outside the setlocal block if you're running this in a larger script.

Important Notes on Non-Compliant Solutions

I’m explicitly rejecting any solutions that rely on PowerShell (e.g., Get-Date cmdlets) or third-party tools, since you specified strictly using Windows Command Prompt (CMD). These methods don’t align with your requirements and won’t be included here.

内容的提问来源于stack exchange,提问作者jes516

火山引擎 最新活动