DateTime.TryParse返回错误(IMO)答案

时间:2015-06-05 15:14:48

标签: asp.net vb.net datetime

我有一个旧的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

当我使用传递fx值“11.16”并且它说“哦是的,这是一个约会 - 2015/11/16”时,我的问题出现了

我尝试使用success = DateTime.TryParse(_str,tempDate),但行为相同。

如果传入的_str可以是从空白字符串到日期到美元金额到街道地址的任何内容,那么最好的方法是什么?显而易见的是重写调用代码,但遗留代码并不是非常实用。任何建议都表示赞赏。

谢谢!

1 个答案:

答案 0 :(得分:0)

Andrew Whitaker对TryParseExact的回答以及一系列日期格式是我特定情况的最佳答案。