问题
I'm trying to write a cmd script that gets the current date and time and formats it into a way that sqlserver can input it as a datetime
.
So far, I have:
@echo off
for /F "tokens=1-4 delims=/ " %%i in ('date /t') do (
set dow=%%i
set mon=%%j
set day=%%k
set yr=%%l
set mydate=%%j/%%k/%%l
)
This prints out 10/22/2010
I have not been able to figure out how to get the time into a usable format. I tried working with time /t
, but it only gives the hours and minutes, and I need the seconds also.
回答1:
Use the %TIME%
pseudo-variable.
You can also use %DATE%
in above script.
Both have the same limitations, in that they depend on your locale. The code is not portable and you'll be up for surprises in other environments. But that's how date and time in cmd works.
回答2:
Alternative approach where %TIME% is in format H:MM:SS.FF and H in range 0 - 23 and can be represented with one digit (based on this article):
set YYYY=%DATE:~10,4%
set MM=%DATE:~4,2%
set DD=%DATE:~7,2%
set HH=%TIME: =0%
set HH=%HH:~0,2%
set MI=%TIME:~3,2%
set SS=%TIME:~6,2%
set FF=%TIME:~9,2%
set dirName=%YYYY%%MM%%DD%
set fileName=%dirName%\%YYYY%%MM%%DD%_%HH%%MI%%SS%.tmp
echo %fileName%
回答3:
Here is the way I went about doing my bat script:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ("%DATE%") do (
SET YYYY=%%c
SET MM=%%a
SET DD=%%b
)
For /f "tokens=1-4 delims=/:." %%a in ("%TIME%") do (
SET HH24=%%a
SET MI=%%b
SET SS=%%c
SET FF=%%d
)
echo %%DATE%%=%DATE%
echo %%TIME%%=%TIME%
echo %YYYY%-%MM%-%DD%_%HH24%-%MI%-%SS%-%FF%
echo %YYYY%/%MM%/%DD% %HH24%:%MI%:%SS%
echo %MM%/%DD%/%YYYY% %HH24%:%MI%:%SS%
echo YYYY=%YYYY%
echo MM=%MM%
echo DD=%DD%
echo HH24=%HH24%
echo MI=%MI%
echo SS=%SS%
echo FF=%FF%
pause
You can now remove all the echos and use this from any bat file by typing:
call SetDateTimeVariables.bat
Example: Creating an archive directory and storing the location:
@echo off
SETLOCAL
call test2.bat
ENDLOCAL&(
SET ARCHIVE_DIR="archive/%YYYY%%MM%%DD%%HH24%%MI%%SS%"
)
MKDIR "%ARCHIVE_DIR%"
回答4:
echo %time:~-5%
http://ss64.com/nt/syntax-substring.html
the last 5 characters of %time% is always seconds dot milliseconds
example output:
33.84
来源:https://stackoverflow.com/questions/4248220/how-can-i-retrieve-the-seconds-part-of-time-in-cmd