PowerShell / PowerShell/PowerShell
Type cast TimeSpan to DateTime relative to now (Get-Date)
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 55.5k
- Forks
- 8.5k
- Avg merge
- 1d 2h
- Merged PRs (30d)
- 88
Description
TimeSpan to DateTime
Currently the following statement produces an error:
[DateTime](New-TimeSpan -Days 7)
InvalidArgument: Cannot convert the "7.00:00:00" value of type "System.TimeSpan" to type "System.DateTime".
The idea is that it would make more sense if it would actually cast to a DateTime type relative to now (Get-Date).
(Get-Date).Add(<TimeSpan>), e.g.: (Get-Date).Add((New-TimeSpan -Days 7)):
Example 1
[DateTime](New-TimeSpan -Days 7) # As of Sunday, December 27, 2020 10:13:18 AM
Sunday, January 3, 2021 10:13:18 AM # Wishful thinking
Example 2
$After = New-TimeSpan -Days -14
$Before = New-TimeSpan -Days -7
Get-EventLog -LogName System -EntryType Error -After $After -Before $Before
Example 3
function Get-WeekDay ([DateTime]$Date) {
"{0:d MMMM yyyy} is a {0:dddd}." -f $Date
}
Get-WeekDay 'January 1, 2021'
1 January 2021 is a Friday.
Get-WeekDay (New-TimeSpan -Days 5) # Instead of: Get-WeekDay (Get-Date).Add((New-TimeSpan -Days 5))
1 January 2021 is a Friday. # Wishful thinking
Related
#14496 New OlderThan and NewerThan parameters for Get-ChildItem cmdlet
The added suggestion You might also consider to accept (besides a DateTime type) a TimeSpan type: will simply be impliciet:
$30DaysAgo = New-TimeSpan -Days -30
Get-ChildItem $Path -Recurse -OlderThan $30DaysAgo
#12305 A simple method for creating TimeSpan objects to enable more user-friendly and simple usage of time-dependent Cmdlets
And together with this purpose it might even get to
(where -OlderThan is just a parameter of [DateTime] type as orginally purposed):
Get-ChildItem $Path -Recurse -OlderThan -30Days
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No implementation files, tests, or entry points are named. Start by reviewing the PowerShell conversion behavior and related issues #14496 and #12305; done would be a decided and tested rule for converting a TimeSpan to a DateTime relative to Get-Date, including the examples shown.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- powershell
- Domain
- cli
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100