New-TimeSpan

创建 TimeSpan 对象。

语法

New-TimeSpan
   [[-Start] <DateTime>]
   [[-End] <DateTime>]
   [<CommonParameters>]
New-TimeSpan
   [-Days <Int32>]
   [-Hours <Int32>]
   [-Minutes <Int32>]
   [-Seconds <Int32>]
   [-Milliseconds <Int32>]
   [<CommonParameters>]

说明

New-TimeSpan cmdlet 创建表示时间间隔的 TimeSpan 对象。 可以使用 TimeSpan 对象从 DateTime 对象中添加或减去时间。

如果没有参数,New-TimeSpan 命令将返回表示零时间间隔的 TimeSpan 对象。

示例

示例 1:创建指定持续时间的 TimeSpan 对象

此命令创建 TimeSpan 对象,持续时间为 1 小时 25 分钟,并将其存储在名为 $TimeSpan的变量中。 它显示 TimeSpan 对象的表示形式。

$TimeSpan = New-TimeSpan -Hours 1 -Minutes 25
$TimeSpan

Days              : 0
Hours             : 1
Minutes           : 25
Seconds           : 0
Milliseconds      : 0
Ticks             : 51000000000
TotalDays         : 0.0590277777777778
TotalHours        : 1.41666666666667
TotalMinutes      : 85
TotalSeconds      : 5100
TotalMilliseconds : 5100000

示例 2:为时间间隔创建 TimeSpan 对象

此示例创建一个新的 TimeSpan 对象,该对象表示运行命令的时间与 2010 年 1 月 1 日之间的间隔。

此命令不需要 Start 参数,因为 Start 参数的默认值为当前日期和时间。

New-TimeSpan -End (Get-Date -Year 2010 -Month 1 -Day 1)

示例 3:从当前日期获取日期 90 天

$90days = New-TimeSpan -Days 90
(Get-Date) + $90days

这些命令返回当前日期后的 90 天日期。

示例 4:发现文件更新后的 TimeSpan

此命令指示自上次更新 about_remote 帮助文件以来的时长。 可以在任何文件或具有 LastWriteTime 属性的任何其他对象上使用此命令格式。

此命令的工作原理是,New-TimeSpanStart 参数具有 LastWriteTime的别名。 通过管道将具有 LastWriteTime 属性的对象传递给 New-TimeSpan时,PowerShell 将 LastWriteTime 属性的值用作 Start 参数的值。

Get-ChildItem $PSHOME\en-us\about_remote.help.txt | New-TimeSpan

Days              : 321
Hours             : 21
Minutes           : 59
Seconds           : 22
Milliseconds      : 312
Ticks             : 278135623127728
TotalDays         : 321.916230471907
TotalHours        : 7725.98953132578
TotalMinutes      : 463559.371879547
TotalSeconds      : 27813562.3127728
TotalMilliseconds : 27813562312.7728

参数

-Days

指定时间跨度中的天数。 默认值为 0。

类型:Int32
Position:Named
默认值:None
必需:False
接受管道输入:False
接受通配符:False

-End

指定时间跨度的结束时间。 默认值为当前日期和时间。

类型:DateTime
Position:1
默认值:Current date and time
必需:False
接受管道输入:True
接受通配符:False

-Hours

指定时间跨度中的小时数。 默认值为 0。

类型:Int32
Position:Named
默认值:None
必需:False
接受管道输入:False
接受通配符:False

-Milliseconds

指定时间跨度长度(以毫秒为单位)。 默认值为 0。

类型:Int32
Position:Named
默认值:None
必需:False
接受管道输入:False
接受通配符:False

-Minutes

指定时间跨度中的分钟数。 默认值为 0。

类型:Int32
Position:Named
默认值:None
必需:False
接受管道输入:False
接受通配符:False

-Seconds

指定时间跨度长度(以秒为单位)。 默认值为 0。

类型:Int32
Position:Named
默认值:None
必需:False
接受管道输入:False
接受通配符:False

-Start

指定时间跨度的开始。 输入表示日期和时间的字符串,例如“3/15/09”或 DateTime 对象,例如 Get-Date 命令中的一个。 默认值为当前日期和时间。

可以使用 Start 或其别名,LastWriteTimeLastWriteTime 别名允许通过管道将具有 LastWriteTime 属性(如文件系统 [System.Io.FileIO]中的文件)的对象传递给 New-TimeSpanStart 参数。

类型:DateTime
别名:LastWriteTime
Position:0
默认值:Current date and time
必需:False
接受管道输入:True
接受通配符:False

输入

DateTime

可以通过管道将表示开始时间的 DateTime 对象传递给此 cmdlet。

输出

TimeSpan

此 cmdlet 返回表示时间跨度的对象。