1

I cannot get the time difference from a certain date using Powershell like below:

$Date = '11/12/2001'
(New-TimeSpan -Start (Get-Date -Date $Date) -End (Get-Date)).ToString("'yyyy' Years 'MM' Months 'dd' Days 'hh' Hours 'mm' Minutes 'ss' Seconds'")

Error:

Exception calling "ToString" with "1" argument(s): "Input string was not in a correct format." 
At line:2 char:1 
+ (New-TimeSpan -Start (Get-Date -Date $Date) -End (Get-Date)).ToString ... 

Why I cannot get the Years and Months elapsed?

Senior Systems Engineer
  • 1,155
  • 2
  • 27
  • 55
  • 2
    You may have to calculate those properties, they are not part of the property set that I get when I feed the result of the command to `get-member`. – Davidw Sep 04 '20 at 14:11

1 Answers1

5

TimeSpan doesn't have years or months.

$Date = "11/12/2001"  
$TimeSpan = (New-TimeSpan -Start (Get-Date -Date $Date)  
Write-Output "$($TimeSpan.ToString("dddd")) Days $($TimeSpan.ToString("hh")) Hours $($TimeSpan.ToString("mm")) Minutes $($TimeSpan.ToString("ss")) Seconds"  

6871 Days 10 Hours 30 Minutes 18 Seconds

Greg Askew
  • 34,339
  • 3
  • 52
  • 81
  • See: [Custom TimeSpan Format Strings](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings) – Daniel Sep 05 '20 at 09:13
  • @Daniel Nothing in that does what the OP is trying to do. – Davidw Sep 05 '20 at 17:35
  • @Davidw What are you on about? The error says `"Input string was not in a correct format."` and the link is the documentation about all the different __valid__ format string. – Daniel Sep 05 '20 at 17:40
  • @Daniel The OP is trying to figure out years and months from the data, that's information not contained in the property set that the command in question produces. – Davidw Sep 05 '20 at 17:45