Reputation: 41
I've got a variable of type string which looks something like this $string = "07/07/2019 18:00". I want to convert this variable into an variable of type datetime. The format should be MM/DD/YYYY HH:MM
$date = '07/07/2019'
$time = '18:00'
$datetime = $date + ' ' + $time
$datetime = [datetime]::ParseExact('$datetime', 'MM/DD/YYYY_HH:MM', $null)
Using the code above, I get an error message telling me:
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
Is there another way to go?
Upvotes: 2
Views: 102
Reputation: 27428
[datetime]'07/07/2019 18:00'
Sunday, July 7, 2019 6:00:00 PM
Or
[datetime]'7/7'
[datetime]'18:00'
[datetime]'6pm'
Then you can add or subtract them, but then the answer is a [timespan].
Upvotes: 2
Reputation: 11254
Your format string used wrong specifiers, namely DD
and YYYY
; see custom date and time formats.
Change your code to
$date = '07/07/2019'
$time = '18:00'
$datetime = $date + ' ' + $time
$datetime = [datetime]::ParseExact($datetime, 'MM/dd/yyyy HH:mm', $null)
$datetime
Also be aware to pass $datetime
as reference and not as single quoted string.
You find above code under this link.
Upvotes: 3