PowerShell: Comparing dates

前端 未结 3 922
被撕碎了的回忆
被撕碎了的回忆 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
    
    0 讨论(0)
  • 2021-02-06 21:50

    I wanted to show how powerful it can be aside from just checking "-lt".

    Example: I used it to calculate time differences take from Windows event view Application log:

    Get the difference between the two date times:

    PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
    

    Object created:

    PS> $Obj
    
    
    Days              : 0
    Hours             : 0
    Minutes           : 31
    Seconds           : 0
    Milliseconds      : 0
    Ticks             : 18600000000
    TotalDays         : 0.0215277777777778
    TotalHours        : 0.516666666666667
    TotalMinutes      : 31
    TotalSeconds      : 1860
    TotalMilliseconds : 1860000
    

    Access an item directly:

    PS> $Obj.Minutes
    31
    
    0 讨论(0)
  • 2021-02-06 22:03

    As Get-Date returns a DateTime object you are able to compare them directly. An example:

    (get-date 2010-01-02) -lt (get-date 2010-01-01)
    

    will return false.

    0 讨论(0)
提交回复
热议问题