Reputation: 15797
Please see the code below:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
Me.Load
Dim str As String = "1-2-2014"
Dim dte As Date = CDate(str)
MsgBox(dte.Month)
End Sub
The date literal is: #1/2/2014#. This is always interpreted as 2nd January 2014 as discussed here: http://msdn.microsoft.com/en-us/library/3eaydw6e.aspx. However, in the code fragment above the date is interpreted as 1st February 2014. Is the local regional settings used when you pass a string?
Upvotes: 0
Views: 2205
Reputation: 38875
You are looking at the Date
Type MSDN docs, but creating a string "1-2-2014"
which is not a Date
type and wont act like one. The note about the order and using #
applies only to a DateTime
variable:
Dim myDt As Date = #1/2/2014#
Also look at what MSDN says about CDate:
In general, hard-coding dates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as #Feb 12, 1969# and #4:45:23 PM#, instead.
As a string, it is difficult to know what format/culture it follows to know how to convert it back. Instead, keep Date-based data items as Date type variables and simple format them for the user, reports, MsgBox etc:
' DISPLAY a date anyway we want, without changing the value:
Console.WriteLine(dt.ToString("hh:mm M/d/yyyy")) ' => 05:55 2/11/2010
Console.WriteLine(dt.ToString("HH.mm M/d/yyyy")) ' => 17.55 2/11/2010
Console.WriteLine(dt.ToString("MM/dd/yyyy HH:mm")) ' => 02/11/2010 17:55
NET and VB are always going to assume a string is in the current culture format, unless told otherwise. CDate
is simplified so you cant pass a format, but other convert functions allow you to specify the culture or format:
Dim myStr As String = "17:55 2/11/2010" ' ad odd date/time format
Dim dtVar As DateTime = DateTime.ParseExact(myDate,
"HH:mm M/dd/yyyy",
Globalization.CultureInfo.InvariantCulture)
Upvotes: 1