我有一个旧的asp经典VB脚本,很久以前被转换为在vb.net中运行,这是一个混乱,但我还不能得到批准重写它。
里面有一个函数,它接受一个字符串,并尝试根据它的内容正确地处理它。
原文为:
Public Shared Function fx(ByVal _str As String) As String
If IsDate(_str) Then
'Dates have to be formated just right for MySQL to accept them
fx = DatePart("yyyy", _str) & "-" & DatePart("m", _str) & "-" & DatePart("d", _str)
ElseIf IsNumeric(_str) Then
'Numbers go in just fine
fx = _str
ElseIf Len(_str) > 0 Then
'If it's not a date and not a number then treat it as a text field and filter it so that MySQL will take it
_str = Trim(_str) 'First trim off any leading and trailing spaces
_str = Replace(_str, "", "\") 'Change all to \
_str = Replace(_str, "'", "''") 'Change all ' to ''
fx = _str
Else
fx = ""
End If
End Function
我的问题来了,当我使用pass fx值"11.16",它说"哦,是的,这是一个日期- 2015/11/16"
我尝试使用success = DateTime.TryParse(_str,tempDate)
,但它的行为相同。
如果传入的_str可以是任何东西,从空白字符串到日期到美元金额到街道地址,那么最好的方法是什么?最明显的方法是重写调用代码,但使用不太实用的遗留代码。如有任何建议,欢迎。
谢谢!
Andrew Whitaker对TryParseExact
和日期格式数组的回答是对我的特殊情况的最佳回答。
Public Shared Function fx(ByVal _str As String) As String
If IsDate(_str) Then
'Dates have to be formated just right for MySQL to accept them
fx = DatePart("yyyy", _str) & "-" & DatePart("m", _str) & "-" & DatePart("d", _str)
ElseIf IsNumeric(_str) Then
'Numbers go in just fine
fx = _str
ElseIf Len(_str) > 0 Then
'If it's not a date and not a number then treat it as a text field and filter it so that MySQL will take it
_str = Trim(_str) 'First trim off any leading and trailing spaces
_str = Replace(_str, "", "\") 'Change all to \
_str = Replace(_str, "'", "''") 'Change all ' to ''
fx = _str
Else
fx = ""
End If
End Function