计算两个时间戳之间的时差

时间:2018-08-13 12:59:47

标签: powershell datetime

我想计算两个时间戳之间的差值,即使是秒也是如此,这是我的代码段:

#Start Timer
$Start_Timer = (Get-Date).DateTime
Write-Host "Start Timer is ---> $Start_Timer"
#End Timer
$End_Timer = (Get-Date).DateTime
Write-Host "End Timer is ---> $End_Timer"
$Current_Time_End = (Get-Date).DateTime
$TotalExecutionTime = $End_Timer - $Start_Timer

以上代码的输出为:

Start Timer is ---> Monday, August 13, 2018 6:21:18 PM
End Timer is ---> Monday, August 13, 2018 6:22:55 PM

产生错误

Cannot convert value "Monday, August 13, 2018 6:22:55 PM" to type
"System.Int32". Error: "Input string was not in a correct format."
At D:\Eclipse_Repository\self_repo\jmallick\FileMover.ps1:55 char:1
+ $TotalExecutionTime = $End_Timer - $Start_Timer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

我在这里做错了什么?

4 个答案:

答案 0 :(得分:2)

我用这个

static element_t find_child(element_t element, const gchar *name)
{
      for (xmlNode *node = element->children; node; node = node->next)
          if (xmlStrcmp(node->name, (const xmlChar *)name) == 0)
              return node;
      return NULL;
}

输出变量示例:

$t1 = (get-date)
$t2 = (get-date)
$tdiff = $t2-$t1

答案 1 :(得分:1)

(Get-Date).DateTime是一个字符串,因此您无法进行数学运算。您可以使用(Get-Date).DateTime.gettype().fullname进行验证。

在纯日期对象上使用减法,例如$beforeTime = Get-Date将是您想要做的。这还将返回TimeSpan个对象

(get-date) - ((get-date).addhours(-1))

也请阅读此relevant post about calculating execution time in .Netusing StopWatch in PowerShell

答案 2 :(得分:1)

我建议使用[StopWatch]进行性能评估。请参见以下示例:

$timer = [System.Diagnostics.Stopwatch]::StartNew()
#do your job
$timer.Stop()

#get timespan
$timer.Elapsed

答案 3 :(得分:0)

使用此: url 您将以多个增量(天,秒等)表示时差。