Skip to content

Instantly share code, notes, and snippets.

@trackd
Last active October 30, 2023 21:57
Show Gist options
  • Save trackd/6eb957699a7ed12a0dd30d8bdc19ed2a to your computer and use it in GitHub Desktop.
Save trackd/6eb957699a7ed12a0dd30d8bdc19ed2a to your computer and use it in GitHub Desktop.
datetime_conversion_tests.ps1
using namespace System.Globalization
# suppress all the errors from the conversion attempts.
$ErrorActionPreference = 'SilentlyContinue'
Remove-Variable fails, success, results, test*
# clean up old runs if run interactively.
filter Convert-DateTimeProperties {
$_.PSObject.Properties | ForEach-Object {
if ($_.Name -match 'date$|time$' -and $_.Value -is [string]) {
# these methods give almost the same results.
$_.Value = $_.Value -as [datetime]
# $_.Value = Get-Date -Date $_.Value
# $_.Value = [DateTime]::Parse($_.Value, [CultureInfo]::InvariantCulture, [DateTimeStyles]::RoundtripKind)
}
}
$_
}
$date = [Datetime]::Now
$dateFormats = (Get-Culture -ListAvailable).DateTimeFormat.GetAllDateTimePatterns() | Sort-Object -Unique
$Testdata = $dateFormats | ForEach-Object {
$locdate = $date.ToString($_,[CultureInfo]::InvariantCulture)
[PSCustomObject]@{
Format = $_
ToString = $locdate
Datetime = $locdate
}
}
$results = $Testdata | Convert-DateTimeProperties
$fails = $results | Where-Object { $_.Datetime -isnot [datetime] }
$success = $results | Where-Object { $_.Datetime -is [datetime] }
[PSCustomObject]@{
Fails = $fails.Count
Success = $success.Count
Total = $Testdata.Count
FailsPercent = ($fails.Count / $Testdata.Count * 100).ToString('N2')
SuccessPercent = ($success.Count / $Testdata.Count * 100).ToString('N2')
}
<#
[Datetime]::Now.GetDateTimeFormats()
# these are pretty bad..
[datetime]$_.Value = $_.Value
$_.Value = [datetime]$_.Value
$_.Value = [DateTime]::Parse($_.Value, [CultureInfo]::InvariantCulture, 'None')
# not tested properly.
$dt = $null
[DateTime]::TryParseExact($_.Value, $dateFormats, [CultureInfo]::InvariantCulture, 'None', [ref]$dt)
$_.Value = [DateTime]::Parse($_.Value, [CultureInfo]::InvariantCulture, 'None')
$dateResult = $null
foreach ($format in $dateFormats) {
if ([DateTime]::TryParseExact($_.Value, $dateFormats, [CultureInfo]::InvariantCulture, [DateTimeStyles]::RoundtripKind, [ref]$dateResult)) {
break
}
}
if ($dateResult) {
$_.Value = $dateResult
}
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment