自动日期重新格式化

时间:2019-03-07 21:35:48

标签: autoit data-conversion

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

$d = "March 17,2019"

实际上,我的代码没有像这样设置d的值,但是出于参数考虑,让我们假设d以所示格式保存字符串日期。

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

谢谢

2 个答案:

答案 0 :(得分:2)

再提供一个基本代码供您参考

$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)

答案 1 :(得分:1)

$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中使用月份。 在示例代码中,这将从03/17/2019返回March 17,2019。 如果_MyDate()失败,则将@error设置为1的值。

StringFormat在每个日期段使用%02d/%02d/%d,这会强制 月和日的两位零填充。如果零填充不是 然后删除02%之间的d

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

例如

$sFormattedDate = _MyDate($d, 2)

StringRegExp中的模式使用:

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

使用括号从日期字符串中获取3个细分。


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

$d = "March 17,2019"

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