CDATE 如何在 VB.NET 上执行从字符串到日期的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30432836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:09:34  来源:igfitidea点击:

How CDATE perform its conversion from string to date on VB.NET

vb.netdate

提问by pvzkch

I just want to ask how VB.NET perform is conversion of date from string. I am currently designing a database view and convert the date into MMddyyyyformat, but I am worried that CDATE it will read it as ddMMyyyy.

我只是想问一下VB.NET如何执行从字符串转换日期。我目前正在设计一个数据库视图并将日期转换为MMddyyyy格式,但我担心 CDATE 会将其读取为ddMMyyyy.

I want it to make it shorter and converting the date using CDATE instead of using the traditional M/d/yyyy h:mm:ss tt.

我希望它缩短并使用 CDATE 而不是使用传统的M/d/yyyy h:mm:ss tt.


Example:


例子:

Dim myDate As Date = CDate(DataTable.Rows(0).Item("DateValue").ToString())

回答by SSS

CDate depends on the control panel regional settings and is not recommended - you should use Date.ParseExactinstead

CDate 取决于控制面板的区域设置,不推荐使用 - 您应该Date.ParseExact改用

Const MyDateFormat As String = "MMddyyyy"

Dim dte As Date = #2/1/2003#
'convert the date to a string
Dim strDate As String = dte.ToString(MyDateFormat)
'convert the string back to a date
Dim dte2 As Date = Date.ParseExact(strDate, MyDateFormat, System.Globalization.CultureInfo.InvariantCulture)

If dte = dte2 Then
  MsgBox("They're the same :-) " & strDate)
Else
  MsgBox("They're different :-(")
End If

For your code, it would look like:

对于您的代码,它看起来像:

Dim myDate As Date = Date.ParseExact(DataTable.Rows(0).Item("DateValue").ToString(), "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture)