windows 批量获取当前日期月份和年份的安全方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12635541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:56:01  来源:igfitidea点击:

Safe way to get current day month and year in batch

windowsdatebatch-file

提问by Ivaylo Strandjev

I am trying to write a batch script that will get the current day, month and year in a safe manner(i.e. independent of the date format). Unfortunately all the internet sources I have found propose something like:

我正在尝试编写一个批处理脚本,它将以安全的方式(即独立于日期格式)获取当前的日期、月份和年份。不幸的是,我发现的所有互联网资源都提出了类似的建议:

   SET CURRENT_DATE=%DATE: =0%
   SET YEAR=%DATE:~-4%
   SET MONTH=%DATE:~3,2%
   SET DAY=%DATE:~5,2%

This will work if my date is in format yyyy/mm/dd or yyyy-mm-dd but will not if it is in format yy-mm-dd or some other format. Is there a safe way to get the year, month and day?

如果我的日期格式为 yyyy/mm/dd 或 yyyy-mm-dd,这将有效,但如果它的格式为 yy-mm-dd 或其他格式,则无效。有没有安全的方法来获取年、月和日?

And one more question - is it possible to know what the day separator is(/in the first case and -in the other cases).

还有一个问题 - 是否有可能知道日期分隔符是什么(/在第一种情况下和-其他情况下)。

回答by foxidrive

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher.

此代码的前四行将在 XP Pro 及更高版本中为您提供可靠的 YY DD MM YYYY HH Min Sec 变量。

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

Here is a VBS solution:

这是一个 VBS 解决方案:

  :: date time using WSH/VBS
  :: datetime.bat V4.2
  ::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  ::
  :: This uses Windows Scripting Host to set variables to
  :: the current date/time/day/day_number/week_of_year etc
  :: for Win9x/ME/NT/W2K/XP/Vista/Win7/Win8 etc
  :: Thanks go to Todd Vargo for his scripting
  ::
  ::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  @echo off
  set TmpFile="%temp%.\tmp.vbs"
  echo> %TmpFile% n=Now
  echo>>%TmpFile% With WScript
  echo>>%TmpFile% .Echo "set m1="   + monthname(month(n), true)
  echo>>%TmpFile% .Echo "set m2="   + monthname(month(n), false)
  echo>>%TmpFile% .Echo "set woy="  + CStr(datepart("ww", n))
  echo>>%TmpFile% .Echo "set year=" + CStr(Year(n))
  echo>>%TmpFile% .Echo "set yr="   + Right(Year(n),2)
  echo>>%TmpFile% .Echo "set month="+ Right(100+Month(n),2)
  echo>>%TmpFile% .Echo "set day="  + Right(100+Day(n),2)
  echo>>%TmpFile% .Echo "set hour=" + Right(100+Hour(n),2)
  echo>>%TmpFile% .Echo "set min="  + Right(100+Minute(n),2)
  echo>>%TmpFile% .Echo "set sec="  + Right(100+Second(n),2)
  echo>>%TmpFile% .Echo "set dow="  + WeekDayName(Weekday(n),1)
  echo>>%TmpFile% .Echo "set dow2=" + WeekDayName(Weekday(n))
  echo>>%TmpFile% .Echo "set iso="  + CStr(1 + Int(n-2) mod 7)
  echo>>%TmpFile% .Echo "set iso2=" + CStr(Weekday(n,2))
  echo>>%TmpFile% End With
  cscript //nologo "%temp%.\tmp.vbs" > "%temp%.\tmp.bat"
  call "%temp%.\tmp.bat"
  del  "%temp%.\tmp.bat"
  del  %TmpFile%
  set TmpFile=
  set stamp=%year%-%month%-%day%.%hour%_%min%_%sec%

  if not "%~1"=="" goto :EOF

  echo The year  is "%year%" or "%yr%"
  echo The month is "%month%" "%m1%" "%m2%"
  echo The day   is "%day%" "%dow%" "%dow2%"
  echo.
  echo ISO8601 Day-Of-Week number is "%iso%" and week of year is: "%woy%"

  echo.
  echo The time in hh:mm:ss is "%hour%:%min%:%sec%"
  echo The hour   is "%hour%"
  echo The minute is "%min%"
  echo The second is "%sec%"
  echo.

  echo The date and time stamp is "%stamp%"
  echo.
  echo date A yyyymmdd "%year%%month%%day%"
  echo date B mmddyyyy "%month%%day%%year%"
  echo date C ddmmyyyy "%day%%month%%year%"
  echo date D yymmdd   "%yr%%month%%day%"
  echo date E mmddyy   "%month%%day%%yr%"
  echo date F ddmmyy   "%day%%month%%yr%"
  pause
  :: datetime.bat
  ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

回答by jeb

First, you could retrieve the current settings from the registry (somewhere).
The format and also the separators.

首先,您可以从注册表(某处)检索当前设置。
格式和分隔符。

But it's easier to use wmicinstead, it has always the same format, the only drawback is, that it's take a bit of time, each time you start it.

但是它更容易使用wmic,它始终具有相同的格式,唯一的缺点是每次启动它都需要一些时间。

Modified sample from SO: Log Date/Time

来自SO 的修改示例:日志日期/时间

@echo off
setlocal EnableDelayedExpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
        SET /A FTIME=%%B*10000+%%C*100+%%E
    )
)
ECHO !FDATE! - !FTIME!

回答by FifthAxiom

Extract Day, Month and Year (locale-independent)

提取日、月和年(与语言环境无关)

I wouldn't use WMIC since it's very high on resources and takes awhile to complete, especially on slower computers. The following script takes the users' localization from the registry, which is locale-independent. As far as I know is is the only batch solution that works. Of course you can also use a call to a VBScript but for me that's off-topic.

我不会使用 WMIC,因为它占用大量资源并且需要一段时间才能完成,尤其是在速度较慢的计算机上。以下脚本从与区域设置无关的注册表中获取用户的本地化。据我所知,这是唯一有效的批处理解决方案。当然,您也可以使用对 VBScript 的调用,但对我来说这是题外话。

@echo off

::: Begin set date
setlocal EnableExtensions EnableDelayedExpansion

:: Determine short date format (independent from localization) from registry
for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do ( 

    :: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
    set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"

    :: Now assign the date values to the new vars
    for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
)


:: Print the values as is
echo.
echo This is the original date string --^> %date%
echo These are the splitted values    --^> Day: %d%, Month:%m%, Year: %y%.
echo.

endlocal

Extract only the Year

仅提取年份

For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution. It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.

对于我编写的脚本,我只想提取年份(与语言环境无关),因此我想出了这个 oneliner,因为我找不到任何解决方案。它使用“DATE”变量、多个分隔符并检查大于 31 的数字。那将是当前年份。与其他一些解决方案相比,它的资源不足。

@echo off

setlocal EnableExtensions

for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )

echo And the year is... %_YEAR%.
echo.

endlocal