Get-Date not converting strings to dates

Hi, I'm having some issues converting a string variable to a time variable so that I can input them into a IF statement. Here is how i'm doing it at the moment -  

    $source = $row.CreationTime
    $dest = $result.CreationTime
    $Source = Get-Date "$source" -Format d
    $dest = Get-Date "$dest" -Format d
    write-host "source = "$source.GetType()
    write-host "dest = "$dest.GetType()

I found that i was not getting the results that I expected in my if statements. So I put GetType() on the end of the variables and lo and behold, they were still strings. How could I alter this code to correctly convert the strings to dates, so that I can compare them correctly?

Thank you.

August 27th, 2015 5:33am

Hello,

declaration for datetime.

 [datetime]$Source = Get-Date "$source" -Format d

Regards,

Free Windows Admin Tool Kit Click here and download it now
August 27th, 2015 5:47am

Hi, I believe that this converts it to a american date format? How would I change it to a British format? for example  - 27/08/2015 instead of 08/27/2015? Because i'm getting the "String was not recognized as a valid DateTime." error when implementing [datetime] in my script.

Thanks.

August 27th, 2015 6:23am

What is this? -  $row.CreationTime

Is it a string? If it is a string then what is its format?

Without that information it is impossible to know what you are doing.

To change formats you must use a date object or set the culture.

Free Windows Admin Tool Kit Click here and download it now
August 27th, 2015 6:34am

$row.CreationTime is a string that looks like this before the get-date - 31/07/2008 10:13:10. This has come out of a .CSV file. Then, I send it through the Get-date so then it looks like 31/07/2008. I have also tried changing my get-date to look like this - $Source = Get-Date $row.CreationTime.ToString() -Format d thinking that it was a variable type error. but obviously not.

Thanks.

August 27th, 2015 6:40am

Just parse it with a compatible culture:

$date=[datetime]::Parse($row.CreationTime,[cultureinfo]'en-GB')

Free Windows Admin Tool Kit Click here and download it now
August 27th, 2015 6:45am

Hi, seems to be working now! Thanks!
August 27th, 2015 6:49am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics