Bunion
Bunion

Reputation: 461

Formatting dates to be able to Subtract them Powershell

I have two objects stored in an array populated from a .csv file, I'm trying to get to a point where i can subtract one from the other.

TEST1 System.String TEST1=20170408
Last Use NoteProperty System.String Last Use=2017-04-18 17:46:42

How can i format the last use into the same format as test 1 whilst also being able to subtract from each other?

I have tried the below

$dt_last_use =$_."Last Use".Split(' ') |Select -First 1

but i get this output from it

2016-12-29

My end goal is to be able to something like this

                    #$dt_last_use =$_."Last Use".Split(' ') |Select -First 1
                    #$today = get-date

                    #$diff = ( $today -$dt_last_use)

Thanks for the help

Upvotes: 1

Views: 780

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23355

Per the comments, you can do the Last Use date just by casting it as a [datetime] object. For the Test1 date you'd need to use the ParseExact method which allows you to define a datetime format based on certain tokens to match the format in your text string:

$LastUse = "2017-04-18 17:46:42"
$dt_last_use = [datetime]$datestring

$Test1 = '20170408'
$dt_test1 = [DateTime]::ParseExact($Test1,"yyyyMMdd", $null)

$today = (get-date)

$difflastuse = $today - $dt_last_use
$difftest1 = $today - $dt_test1

Obviously adapt the $LastUse and $Test1 variables to $_."last use" and $_.test1 for your circumstance, the above is just a complete/verifiable example.

Upvotes: 2

Related Questions