PowerShell: Comparing dates

前端 未结 3 921
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 21:01

I am querying a data source for dates. Depending on the item I am searching for, it may have more than date associated with it.

get-date ($Output | Select-Object         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 21:50

    Late but more complete answer in point of getting the most advanced date from $Output

    ## Q:\test\2011\02\SO_5097125.ps1
    ## simulate object input with a here string 
    $Output = @"
    "Date"
    "Monday, April 08, 2013 12:00:00 AM"
    "Friday, April 08, 2011 12:00:00 AM"
    "@ -split '\r?\n' | ConvertFrom-Csv
    
    ## use Get-Date and calculated property in a pipeline
    $Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
        Sort-Object Date | Select-Object -Last 1 -Expand Date
    
    ## use Get-Date in a ForEach-Object
    $Output.Date | ForEach-Object{Get-Date $_} |
        Sort-Object | Select-Object -Last 1
    
    ## use [datetime]::ParseExact
    ## the following will only work if your locale is English for day, month day abbrev.
    $Output.Date | ForEach-Object{
        [datetime]::ParseExact($_,'ffffdd, MMMM dd, yyyy hh:mm:ss tt',$Null)
    } | Sort-Object | Select-Object -Last 1
    
    ## for non English locales
    $Output.Date | ForEach-Object{
        [datetime]::ParseExact($_,'ffffdd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
    } | Sort-Object | Select-Object -Last 1
    

    ## in case the day month abbreviations are in other languages, here German
    ## simulate object input with a here string 
    $Output = @"
    "Date"
    "Montag, April 08, 2013 00:00:00"
    "Freidag, April 08, 2011 00:00:00"
    "@ -split '\r?\n' | ConvertFrom-Csv
    $CIDE = New-Object System.Globalization.CultureInfo("de-DE")
    $Output.Date | ForEach-Object{
        [datetime]::ParseExact($_,'ffffdd, MMMM dd, yyyy HH:mm:ss',$CIDE)
    } | Sort-Object | Select-Object -Last 1
    

提交回复
热议问题