批处理脚本中的日期时差

时间:2017-11-28 13:34:42

标签: batch-file

我有两个约会时间如下: -

  

开始时间: - 11/27/2017 11:18:14 PM

     

结束时间: - 11/28/2017 4:18:22 AM

如何使用批处理脚本在小时:分钟:秒格式中区分它们?请帮帮我......

2 个答案:

答案 0 :(得分:0)

试试这个(我叫它datediff.bat):

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%


@if (@X)==(@Y) @end JScript comment */

//WScript.Echo(WScript.Arguments.Item(0));

var date1=WScript.Arguments.Item(0);
var date2=WScript.Arguments.Item(1);

function fromStringToDate(dateString) {
    var cd=dateString.split(" ")[0];
    var hm=dateString.split(" ")[1];
    var pm=dateString.split(" ")[2].toLowerCase;

    var mon=parseInt(cd.split("/")[0]);
    var day=parseInt(cd.split("/")[1]);
    var yea=parseInt(cd.split("/")[2]);

    var hou=parseInt(hm.split(":")[0]);
    if(pm=="pm"){
        hou=hou+12;
    }
    var min=parseInt(hm.split(":")[1]);
    var sec=parseInt(hm.split(":")[2]);
    //WScript.Echo(hou+" "+mon);
    //WScript.Echo(yea+","+mon+","+day+","+hou+","+min+","+sec);
    date= new Date(yea,mon,day,hou,min,sec,0);
    //WScript.Echo(date);
    return date;
}

var d1=fromStringToDate(date1);
var d2=fromStringToDate(date2);
var timeDiff = Math.abs(d1.getTime() - d2.getTime());

var diffDays = Math.floor(timeDiff / (1000 * 3600 * 24)); 
timeDiff =(timeDiff-diffDays*1000 * 3600 * 24);

var diffHours= Math.floor(timeDiff / (1000 * 3600));
timeDiff =(timeDiff-diffHours*1000 * 3600);

var diffMinutes= Math.floor(timeDiff / (1000 * 60));
timeDiff =(timeDiff-diffMinutes*1000 * 60);

var diffSeconds= Math.floor(timeDiff / (1000));

WScript.Echo("days: " +diffDays);
WScript.Echo("hours: " +diffHours);
WScript.Echo("minutes: " +diffMinutes);
WScript.Echo("seconds: " +diffSeconds);

并测试它:

datediff.bat "11/27/2017 11:18:14 PM" "11/28/2017 4:18:22 AM"

它仅适用于您发布的格式。

答案 1 :(得分:0)

在批量包装的PowerShell脚本中,小时数为totalhours,
每天差异计数24小时

:: Q:\Test\2017\11\28\SO_47532900.cmd
@Echo off
Set "Start=11/26/2017 11:18:14 PM"
Set "End=11/28/2017 4:18:22 AM"
For /F "usebackqdelims=" %%A in (`
powershell -NoP -C "$TS=New-TimeSpan -Start ([datetime]'%Start%') -End ([datetime]'%End%');'{0}:{1:00}:{2:00}' -f [math]::Floor($TS.TotalHours),$TS.Minutes,$TS.Seconds"
`) Do Set "DTdiffH=%%A"
Set DTdiffH

示例输出:

> SO_47532900.cmd
DTdiffH=29:00:08