字符串到日期转换 - .NET不同的行为

时间:2016-03-08 09:23:28

标签: vb.net

请参阅以下代码:

 Dim dtEstComplDate As Date
 Try
    dtEstComplDate = "08-mar-16"
 Catch ex As Exception
     MessageBox.Show(ex.Message)
 End Try

如果我将我的计算机本地格式设置为英语(美国),'08-mar-16'dtEstComplDate分配为#3/82016# 08-mrz-16 现在,如果我将计算机格式更改为意大利语,则此分配会导致以下异常:

  

“从字符串”08-mar-16“转换为”日期“类型无效。”

我尝试使用意大利语设置的Request。它不起作用。

3 个答案:

答案 0 :(得分:3)

原因是mar是英语月份游行的缩写,而不是意大利语。

不要使用字符串来初始化日期。相反,您应该将Option Strict更改为On。然后,您将学习很多关于.NET方法和类型以及如何编写类型安全代码的知识。如果要初始化Date,可以使用构造函数:dtEstComplDate = New Date(2016, 3, 8)

如果您真的需要将字符串解析为Date,请使用Date.Parse / Date.TryParseDate.ParseExact / Date.TryParseExact

dtEstComplDate = Date.ParseExact("08-mar-16", "dd-MMM-yy", DateTimeFormatInfo.InvariantInfo)

我正在使用InvariantInfo,因为它源自英文格式。

答案 1 :(得分:0)

尝试将其转换为日期更为简单

MSGBOX(CDATE(&#34 01/02/16 34#。)的ToString(" YYYY-MM-DD&#34))

cdate函数会将文本转换为日期

答案 2 :(得分:0)

我希望以下示例可以帮助您理解..为什么会发生这种情况..当您在区域设置中更改区域时...点网代码发生同样的事情......

    Dim dtEstComplDate As Date
    Try

        'Will be the country name you set using datetimesetting
        MessageBox.Show(System.Threading.Thread.CurrentThread.CurrentCulture.Name)

        Dim ukCulture As System.Globalization.CultureInfo
        Dim itCulture As System.Globalization.CultureInfo

        ukCulture = New Globalization.CultureInfo("en-GB")
        itCulture = New Globalization.CultureInfo("it-IT")

        Dim strDate = "08-mar-16"

        'forcing to use uk culture when converting string to date
        System.Threading.Thread.CurrentThread.CurrentCulture = ukCulture

        dtEstComplDate = strDate
        MessageBox.Show(dtEstComplDate)

        'forcing to use italian culture when converting string to date
        System.Threading.Thread.CurrentThread.CurrentCulture = itCulture
        dtEstComplDate = strDate
        MessageBox.Show(dtEstComplDate)

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
相关问题