首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DateTime.TryParse返回错误(IMO)答案

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

Stack Overflow用户
提问于 2015-06-05 15:14:48
回答 2查看 91关注 0票数 0

我有一个很久以前在VB .NET中被转换为运行的老式asp经典VB脚本,这真是一团糟,但我还无法获得重写它的批准。

在那里,它有一个函数,它接受一个字符串,并尝试根据其内容正确地处理它。

它最初的写法是:

代码语言:javascript
复制
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值"11.16“,它说”哦,是的,这是一个日期- 2015/11/16“时,我的问题出现了。

我试过使用success = DateTime.TryParse(_str,tempDate),但它的行为是一样的。

如果传入的_str可以是从空字符串到日期、金额到街道地址的任何东西,那么最好的方法是什么?显而易见的是重写调用代码,但使用遗留代码并不太实际。任何建议都很感激。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-23 16:48:39

安德鲁·惠特克( Andrew )对TryParseExact和一系列日期格式的回答是对我特殊情况的最好回答。

票数 0
EN

Stack Overflow用户

发布于 2021-08-29 03:47:02

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30670058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档