计算批处理文件中两个日期之间的持续时间(DD/MM/YYYY HH:MM:SS)
我想计算以DD/MM/YYYY HH:MM:SS为格式的两个日期之间的持续时间:
I would like to calculate a duration between two dates which have DD/MM/YYYY HH:MM:SS as format:
echo Jours;Mois;Année;hh;mm;JoursF;MoisF;AnnéeF;hhF;mmF;Duration>Duration.csv
REM ====Découper la date en jours, mois et années ==
SET AA1=2018
SET MM1=01
SET JJ1=01
REM REM ====Découper l'heures en heures, Minutes, Secondes ==
SET hh1=01
SET mmm1=20
REM =====saisie deux
REM ====Découper la date en jours, mois et années ==
SET AA2=2019
SET MM2=02
SET JJ2=03
REM ====Découper l'heures en heures, Minutes, Secondes ==
SET hh2=02
SET mmm2=5
REM==== statement condition
IF %AA2% EQU %AA1% IF %MM2% EQU %MM1% IF %JJ2% EQU %JJ1% IF %hh2% EQU %hh1%
IF %mmm2% GTR %mmm1% set /a duration = %mmm2%-%mmm1%
REM===== display duration
Echo %JJ1%;%MM1%;%AA1%;%hh1%;%mmm1%;%JJ2%;%MM2%;%AA2%;%hh2%;%mmm2%;%duration% >>Duration.csv
这是通用的PowerShell解决方案(从批处理文件调用-在任何Windows操作系统上均应工作).您没有说经过的时间应该采用什么格式,所以这是一个概念证明.
Here's a generic PowerShell solution (invoked from a batch file—should work on any Windows OS). You didn't say what format the elapsed time should be in, so this is a proof of concept.
SETLOCAL
SET "DATE1=25/06/2018 13:18:25"
SET "DATE2=26/06/2018 09:57:59"
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "((Get-Date -Year %DATE1:~6,4% -Month %DATE1:~3,2% -Day %DATE1:~0,2% -Hour %DATE1:~11,2% -Minute %DATE1:~14,2% -Second %DATE1:~17,2%) - (Get-Date -Year %DATE2:~6,4% -Month %DATE2:~3,2% -Day %DATE2:~0,2% -Hour %DATE2:~11,2% -Minute %DATE2:~14,2% -Second %DATE2:~17,2%)).ToString()" <NUL
这产生
20:39:33.9995000
日期格式必须必须使用零填充值(可能是您所描述的值),此方法才能正常工作.
The date format must have zero-padded values (probably what you described) for this method to work.
如果日期的格式与您的系统区域设置相匹配(我假设您在欧洲或加拿大),则可以大大简化PowerShell命令,从而使Windows可以为您执行所有解析.在这种情况下,零填充不再是必需的.
If the date is in a format that matches your system locale (I presume you're in Europe or Canada), the PowerShell command can be greatly simplified, allowing Windows to do all the parsing for you. Zero-padding is no longer a requirement in this case.
SETLOCAL
SET "DATE1=25/06/2018 13:18:25"
SET "DATE2=26/06/2018 09:57:59"
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "((Get-Date '%DATE2%') - (Get-Date '%DATE1%')).ToString()" <NUL
如果希望将经过的时间表示为秒,分钟,小时或天的十进制数,则可以使用.TotalSeconds
(或.TotalMinutes
,.TotalHours
或TotalDays
)代替
If you wanted the elapsed time as a decimal number of seconds, minutes, hours, or days, you could just use, .TotalSeconds
(or .TotalMinutes
, .TotalHours
, or TotalDays
) instead of .ToString()
.
在我看来,日期库是完成这项工作的正确工具. CMD只能执行整数算术,而其他大多数逻辑都是痛苦的.如果可以将工作简化为简单的算术(在这方面@aacini的解决方案很酷),那么它可能还不错.否则,不要重新发明轮子.
In my opinion, date libraries are the right tool for the job. CMD can only do integer arithmetic and most other logic is painful. If the job can be reduced to simple arithmetic (@aacini's solution is cool in this regard), then it might not be too bad. Otherwise, don't reinvent the wheel.