我对vb 2008和MySQL服务器中的日期格式有一些问题。 我想要一个文本框输入接受这种格式的日期dd-mm-yyyy和dd / mm / yyyy然后将其转换为mysql日期格式yyyy-mm-dd。
截至目前,我还不知道如何开始这种日期格式化,但我想将其放在模块中。
非常感谢任何想法。谢谢
答案 0 :(得分:1)
用户倾向于以各种格式输入日期,例如dd-MM-yyyy,dd / M / yyyy,d.MM.yyyy等。虽然我们可以使用验证器来限制它们,正则表达式等。但不使用任何正则表达式,验证器和插件,我们可以使用以下方法验证和转换以下列格式作为字符串传递的日期:
day[separator]month[separator]year
日期可以在d
或dd
(3,03),
月份可以是M
或MM
(7,07),
年份可以是yy
或yyyy
(2015年5月15日)和
分隔符可以是[space]
,/
,.
或-
可以采用混合格式,例如
dd-MM-YYYY
,dd/MM/YYYY
,dd.MM.YYYY
,dd MM yyyy
,d-M-YY
,d/M/YY
,d.M.YY
,d M yy
,{{ 1}},d-MM-YYYY
,dd/M/YYYY
等。
此函数将日期作为上述任何格式的字符串参数,并在dd.MM.YY
中验证并返回日期。它会检查闰年并将1970年作为检查从yyyy-MM-dd
转换为yy
格式的基础。
yyyy
您可以简单地将其称为
Public Function DMYtoYMD(stDate As String) As String
Dim blValidDate As Boolean = True
While stDate.Contains(" ")
stDate = stDate.Replace(" ", " ")
End While
stDate = stDate.Trim.Replace(" ", "-").Replace("/", "-").Replace(".", "-")
Dim stFinalDate As String = ""
If stDate.Length > 0 Then
Dim mc As String() = stDate.Split(CChar("-"))
Dim inDay As Integer = CInt(mc(0))
Dim inMonth As Integer = 0
If IsNumeric(mc(1)) Then
inMonth = CInt(mc(1))
Else
For inMonthNo As Integer = 1 To 13
If inMonthNo = 13 Then
inMonth = 0
blValidDate = False
Return ""
ElseIf MonthName(inMonthNo, True).ToLower = mc(1).ToLower.Substring(0, 3) Then
inMonth = inMonthNo
Exit For
End If
Next
End If
Dim inYear As Integer = Math.Abs(CInt(mc(2)))
stFinalDate = ""
If inYear < 100 Then
'use above condition to convert 0 (i.e. 2000) to current year to 20xx and all others to 19xx
'If inYear >= (CInt(Format(Today, "yy")) + 1) Then
'use this condition to convert all yy year above 70 to 19xx and all others to 20xx
If inYear > 70 Then
inYear += 1900
Else
inYear += 2000
End If
'ignoring year from 101 to 999 (as per my specific requirement for the project). valid dates are to be from 1900 or above
ElseIf inYear < 1900 Then '101 to 999
stFinalDate = ""
blValidDate = False
End If
If (inMonth < 1 OrElse inMonth > 12) Then
stFinalDate = ""
blValidDate = False
ElseIf (inDay < 1 OrElse inDay > 31) Then
stFinalDate = ""
blValidDate = False
ElseIf ((inMonth = 4 OrElse inMonth = 6 OrElse inMonth = 9 OrElse inMonth = 11) AndAlso inDay = 31) Then
stFinalDate = ""
blValidDate = False
ElseIf (inMonth = 2) Then
Dim isleap As Boolean = (inYear Mod 4 = 0 AndAlso (inYear Mod 100 <> 0 OrElse inYear Mod 400 = 0))
If (inDay > 29 OrElse (inDay = 29 AndAlso Not isleap)) Then
stFinalDate = ""
blValidDate = False
End If
End If
If blValidDate Then
stFinalDate = CStr(New Date(inYear, inMonth, inDay))
If Not IsDate(stFinalDate) Then
stFinalDate = ""
Else
stFinalDate = Format(New Date(inYear, inMonth, inDay), "yyyy-MM-dd")
End If
End If
End If
Return stFinalDate
End Function
如果输入日期无效,则此函数返回零长度字符串。它可以进一步修改为包含Dim dtDate As String = ""
dtDate = DMYtoYMD(TextBox1.Text) 'or as Class1.DMYtoYDM as per your code structure
或MMM
格式,以转换为MMMM
,并根据您的要求检查MM
或其他输入格式。