自动数据已重组

问题描述 投票:0回答:2

我有一个变量,它包含一个表示日期的字符串。

$d = "March 17,2019"

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

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

谢谢

autoit data-conversion
2个回答
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
投票
$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,强制月和日的零填充为2位。如果不需要零填充,则删除02%之间的d

如果你想要年份只有2位数,那么使用2作为_MyDate()的第二个参数。

EG

$sFormattedDate = _MyDate($d, 2)

StringRegExp中的模式使用:

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

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


如果你想保持月份不变,只需用/替换空格和逗号。

$d = "March 17,2019"

$sFormattedDate = StringRegExpReplace($d, '[\s,]', '/')
MsgBox(0, @ScriptName, $sFormattedDate)
© www.soinside.com 2019 - 2024. All rights reserved.