获取同一行的日期和时间

Aar*_*ron 26 powershell command-line

我可以使用date /t和time /t获取日期和时间,但它不会彼此相邻显示.我想让它做到这一点并显示如下:

Current Date & Time
-------------------

11/27/2013 10:43:05 AM
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 31

尝试以下(PowerShell):

Get-Date -Format G

27.11.2013 17:10:23
Run Code Online (Sandbox Code Playgroud)

格式是使用系统的区域设置定义的,所以对我而言,这就是我所得到的,但如果您想要的是区域日期/时间格式,它应该显示为您想要的.

(Get-Date).ToString()
Run Code Online (Sandbox Code Playgroud)

可能也会奏效.

更新:

"Date and time is: $((Get-Date).ToString())"
Run Code Online (Sandbox Code Playgroud)

  • 将对象转换为字符串时不需要`ToString()`(如果将其嵌入字符串内的子表达式中会发生这种情况). (2认同)

Joe*_*oey 17

在PowerShell中,这是微不足道的:

(Get-Date).ToString('MM/dd/yyyy hh:mm:ss tt')
Run Code Online (Sandbox Code Playgroud)

在cmd它有点复杂:

rem Get the date and time in a locale-agnostic way
for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
rem Leading zeroes for everything that could be only one digit
set Month=0%Month%
set Day=0%Day%
rem Hours need special attention if one wants 12-hour time (who wants that?)
if %Hour% GEQ 12 (set AMPM=PM) else (set AMPM=AM)
set /a Hour=Hour %% 12
if %Hour%==0 (set Hour=12)
set Hour=0%Hour%
set Minute=0%Minute%
set Second=0%Second%
set Month=%Month:~-2%
set Day=%Day:~-2%
set Hour=%Hour:~-2%
set Minute=%Minute:~-2%
set Second=%Second:~-2%
rem Now you can just create your output string
echo %Month%/%Day%/%Year% %Hour%:%Minute%:%Second% %AMPM%
Run Code Online (Sandbox Code Playgroud)

请注意,在支持这种奇怪的日期和时间格式时浪费了大量代码.必要时前导零.另请注意,无论用户的区域和语言设置如何,此代码都有效.例如,它不依赖于用户的日期格式(对我而言,无论如何都是ISO 8601).