Home > Blockchain >  Why is [datetime] converting this UTC time correctly and how can I replicate that with ParseExact
Why is [datetime] converting this UTC time correctly and how can I replicate that with ParseExact

Time:04-30

I feel silly that I cannot figure this one out on my own.

I have dates coming from the CarbonBlack API e.g. 2022-02-15-172040 which are in UTC

The [datetime] type cast works fine if I remove the seconds portion of the string

PS M:\Scripts> [datetime]"2022-02-15-1720"   
Tuesday, February 15, 2022 12:20:00 PM

I don't understand how it "knows" that is a UTC string. It is correct of course but I expected 5:20pm for the time portion. I wanted the seconds for the date so I went to parse exact as this doesn't match any format strings as far as I know

PS M:\Scripts> [datetime]::ParseExact("2022-02-15-172040", "yyyy-MM-dd-HHmmss" ,[Globalization.CultureInfo]::CurrentUICulture)
Tuesday, February 15, 2022 5:20:40 PM

Which is the time I expected but the incorrect time.

Why is the [datetime] working when I wouldn't expect it to and what do I need to do to the string or static method call for it to treat that as a UTC string with minimal manipulation?

CodePudding user response:

This is because

([datetime]"2022-02-15-1720").Kind

yields 'Local', while

([datetime]::ParseExact("2022-02-15-172040", "yyyy-MM-dd-HHmmss",[CultureInfo]::InvariantCulture)).Kind

returns 'Unspecified'

If you want the result to handle the string as being Local time and then the result should be in UTC, use:

([datetime]::ParseExact("2022-02-15-172040", "yyyy-MM-dd-HHmmss",[CultureInfo]::InvariantCulture, 'AssumeLocal')).ToUniversalTime()

or

$date = [datetime]::ParseExact("2022-02-15-172040", "yyyy-MM-dd-HHmmss",[CultureInfo]::InvariantCulture)
[datetime]::SpecifyKind($date, 'Local').ToUniversalTime()
  • Related