代码之家  ›  专栏  ›  技术社区  ›  buti-oxa

如何检查字符串是否包含日期?

  •  8
  • buti-oxa  · 技术社区  · 16 年前

    param($date = (Get-Date))
    
    if ($date -match "^\d+$")
    {  
        $date = (Get-Date).AddDays($date)
    } 
    elseif ($date -as [DateTime]) 
    {
        $date = [DateTime]::Parse($date)  
    }
    else 
    {  
        'You entered an invalid date'
        exit 1
    }
    

    这是我以前的尝试

    param($date = (Get-Date))
    
    if ($date -as [DateTime]) 
    {
        $date = [DateTime]::Parse($date)  
    }
    elseif ($date -match "^\d+$")
    {  
        $date = (Get-Date).AddDays($date)
    } 
    else 
    {  
        'You entered an invalid date'
        exit 1
    }
    

    当我输入一个数字时,脚本在日期解析行中断。当给定一个数字时,我的“是日期”检查似乎返回true。

    4 回复  |  直到 16 年前
        1
  •  14
  •   buti-oxa    16 年前

    是的,您可以使用(-as[DateTime])检查字符串是否包含日期。我的原始脚本中的问题是,我假设脚本输入参数是字符串。显然,数字参数会自动转换为整数,除非它是用引号键入的。所以,我应该写

    if ([string]$date -as [DateTime])  
    

    强制将可能的数字转换回字符串,就像基思在回答中所做的那样。

    同样的缺陷也适用于我的整数检查。脚本在给定10月3日时失败(不带引号)。PS在这里创建数组吗?

    为什么检查成功时解析失败?约翰尼斯解释说。表情

    $date -as [DateTime]
    

    指示PS将输入转换为日期。转换数字是有意义的(日期1是0001年1月1日),所以在给定数字时不会失败。表情

    [DateTime]::Parse($date)
    

    不管怎样,我两个都用是浪费。首先,我在条件中转换为date,只是为了丢弃结果。然后,我用不同的语法重新创建结果。我把它改成

    $date = $date -as [DateTime];
    if (!$date)
    {  
        'You entered an invalid date'
        exit 1
    }
    

        2
  •  10
  •   Keith Hill    16 年前

    您可以让.NET Framework帮助您:

    function ParseDate([string]$date)
    {
        $result = 0
        if (!([DateTime]::TryParse($date, [ref]$result)))
        {
            throw "You entered an invalid date: $date"
         }
    
        $result
    }
    
    ParseDate 'June 51, 2001'
    
        3
  •  6
  •   Joey Gumbo    16 年前

    DateTime ,只是因为 日期时间 只是幕后的一个数字。

    日期时间 有一个 Ticks 尽管我到目前为止还没有找到它的用途,但我还是用了那些滴答声。

    PS> ([datetime]1234).Ticks
    1234
    

    但这就是为什么你可以给 日期时间 它是有效的。这可能只是很久以前的一次约会:-)

    日期时间

        4
  •  0
  •   JD2MCSE    8 年前

    function isDate([string]$strdate)
    {
        [boolean]($strdate -as [DateTime])
    }
    
        5
  •  0
  •   galaxis    6 年前

    if( $date -is [DateTime] ) {...}

    还有 -isNot ,作为对 !(...-is...) ; 有时会出现“!”扫描一堆代码时丢失:)

    推荐文章