【问题标题】:Autoit Date reformat自动日期格式
【发布时间】:2019-03-07 21:35:47
【问题描述】:

我有一个变量,其中包含一个代表日期的字符串。

$d = "March 17,2019"

实际上,我的代码并没有像那样设置 d 的值,但是为了论证,我们假设 d 以所示格式保存一个字符串日期。

有没有一种简单的方法可以将 d$ 字符串改为以下格式:mm/dd/yy 格式?

谢谢

【问题讨论】:

    标签: autoit data-conversion


    【解决方案1】:

    还有一个基本代码供你参考

    $d1 = "March 17,2019"
    $year=StringRight($d1,2) ; if you want like 2019 use StringRight($d1,4)
    $rightstr = StringLeft($d1,(StringLen($d1)-5))
    $test = StringSplit($rightstr, " ")
    $mon = $test[1]
    $day = $test[2]
    Local $mon1
    Local $aMMM[12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    for $i =0 to 11
        if $mon = $aMMM[$i] Then
            $mon1 = $i+1
        EndIf
    Next
    $mon1= StringFormat("%02d", $mon1)
    $finaldate = $day&"/"&$mon1&"/"&$year
    MsgBox(1,"",$finaldate)
    

    【讨论】:

      【解决方案2】:
      $d = "March 17,2019"
      
      $sFormattedDate = _MyDate($d)
      
      If Not @error Then
          MsgBox(0, @ScriptName, $sFormattedDate)
      EndIf
      
      Func _MyDate($sDate, $iYearLen = 4)
          ; Get month, day and year from a string (3 = return array of global matches).
          $aDate = StringRegExp($sDate, '(\w+)\s+(\d{1,2}),(\d{4})', 3)
      
          If UBound($aDate) = 3 Then
              ; Create an array of months.
              $aMonths = StringSplit('January|February|March|April|May|June|July|August|September|October|November|December', '|')
      
              ; Match month and return in mm/dd/yy format.
              For $i1 = 1 To UBound($aMonths) -1
                  If $aDate[0] = $aMonths[$i1] Then
                      If $iYearLen <> 4 Then
                          $aDate[2] = StringRight($aDate[2], $iYearLen)
                      EndIf
      
                      Return StringFormat('%02d/%02d/%d', $i1, $aDate[1], $aDate[2])
                  EndIf
              Next
          EndIf
      
          ; Return error 1 if month is not matched.
          Return SetError(1, 0, '')
      EndFunc
      

      使用正则表达式从日期字符串中获取月、日和年。 如果月份与月份数组匹配,则数组索引为 月份在 StringFormat 中使用。 这将在示例代码中从March 17,2019 返回03/17/2019。 如果_MyDate() 失败,则将@error 设置为1 的值。

      StringFormat 在每个日期段上使用 %02d/%02d/%d 月份和日期的 2 位数的零填充。如果零填充不是 需要然后删除%d之间的02

      如果您希望年份只有 2 位,则使用 2 作为第二个 _MyDate()的参数。

      例如

      $sFormattedDate = _MyDate($d, 2)
      

      StringRegExp 中的模式使用:

      • \w 匹配一个单词字符。
      • \d 匹配一个数字。
      • \s 匹配空格。

      括号用于从日期字符串中获取 3 段。


      如果您想保持月份不变,只需替换空格和 带有/ 的逗号。

      $d = "March 17,2019"
      
      $sFormattedDate = StringRegExpReplace($d, '[\s,]', '/')
      MsgBox(0, @ScriptName, $sFormattedDate)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-20
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 2021-12-04
        • 2012-03-14
        相关资源
        最近更新 更多