powershelldatetimecultureinfo

How to format a dateTime-string into FullDatetimeFormat of a different culture?


I need a string-output of a dateTime-Value in the FullDateTime-format of a different culture. The result should be identical to the output of this command on a system running under the target-culture (here 'de-DE'):

$date = [datetime]::new(2022,2,28,10,33,0)
$date.ToString('F')
# Montag, 28. Februar 2022 10:33:00

This is the Powershell-code that I expected to work:

$de = [cultureInfo]::new('de-DE') # sample of any target-culture
[datetime]::ParseExact($date, $de.DateTimeFormat.FullDateTimePattern, $de)

...but that throws an error.

I cannot work with a fixed string format in ParseExact in my project, because I need to respect any (manual) modification of the DateTime-format made for that culture.


Solution

  • The answer was so easy at the end. 'toString' has a 2nd parameter:

    $date = [datetime]::new(2022,2,28,10,33,0)
    $de = [cultureInfo]::new('de-DE')
    $date.ToString($de.DateTimeFormat.FullDateTimePattern, $de)
    

    That works for any other target-cultures in the same way.