CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Converting Date Strings to DateTime Objects in Different Cultures

👀 Views: 100 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
powershell datetime culture PowerShell

I'm working on a project and hit a roadblock. I'm not sure how to approach I'm trying to implement I've looked through the documentation and I'm still confused about I'm having trouble converting date strings into `DateTime` objects using PowerShell 7.3 when the input format varies based on different cultures... I've tried using `Get-Date` but it seems to unexpected result for certain date formats. For example, when I run the following code: ```powershell $dateString = '31/12/2023' $date = Get-Date $dateString -ErrorAction Stop ``` I get an behavior that says `Get-Date : String was not recognized as a valid DateTime.` This happens because my system culture is set to 'en-US', which expects the date format to be 'MM/dd/yyyy'. To tackle this, I tried specifying the culture explicitly: ```powershell $date = [System.Globalization.CultureInfo]::CreateSpecificCulture('en-GB') $dateTime = [DateTime]::ParseExact($dateString, 'dd/MM/yyyy', $date) ``` However, I'm still working with issues when trying to handle an array of dates. When I run this: ```powershell $dateStrings = @('31/12/2023', '01/01/2024') $dates = foreach ($ds in $dateStrings) { [DateTime]::ParseExact($ds, 'dd/MM/yyyy', $date) } ``` I get the behavior `want to convert 'System.Object[]' to the type 'System.DateTime'`. It seems like PowerShell is not able to handle multiple date strings in this way. What is the best approach to convert an array of date strings that are in different formats based on culture? Is there a more efficient way to handle this situation without running into parsing errors? I'm working on a service that needs to handle this. Has anyone else encountered this? My development environment is Ubuntu. How would you solve this? For reference, this is a production mobile app. The project is a service built with Powershell. Hoping someone can shed some light on this. This is my first time working with Powershell 3.10.