New Timespan - PowerShell
Overview
The New-TimeSpan
command in PowerShell creates a TimeSpan
object representing an interval of time. It is particularly useful for working with dates and times, enabling the calculation and manipulation of elapsed durations.
Syntax
New-Timespan -Start <DateTime> -End <DateTime>
New-Timespan -Seconds <Int64>
New-Timespan -Minutes <Int64>
New-Timespan -Hours <Int64>
New-Timespan -Days <Int64>
New-Timespan -Weeks <Int64>
Options/Flags
- -Start: Specifies the start time of the time span.
- -End: Specifies the end time of the time span.
- -Seconds: Specifies the time span in seconds.
- -Minutes: Specifies the time span in minutes.
- -Hours: Specifies the time span in hours.
- -Days: Specifies the time span in days.
- -Weeks: Specifies the time span in weeks.
Examples
Example 1: Create a time span from a start and end time
$startTime = Get-Date "2023-03-08 10:00 AM"
$endTime = Get-Date "2023-03-08 11:30 AM"
$timeSpan = New-Timespan -Start $startTime -End $endTime
Example 2: Create a time span from seconds
$timeSpan = New-Timespan -Seconds 3600
Example 3: Convert a time span to a string
$timeSpan.ToString()
Common Issues
- Ensure that the specified -Start and -End parameters are valid
DateTime
objects. - Avoid using negative values for time span quantities (e.g., -Seconds, -Minutes, -Hours).
Integration
The New-TimeSpan
command can be combined with other PowerShell commands for various tasks:
- Use
Add-TimeSpan
to add a time span to aDateTime
object. - Use
Subtract-TimeSpan
to subtract a time span from aDateTime
object. - Use
Compare-TimeSpan
to compare two time spans.