Ishan
Ishan

Reputation: 4028

Date format issue in vb.net

I am trying to parse a date from a textbox and store it in a date variable

Dim enddt_2 As Date = Date.ParseExact(txtenddt.Text, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)  'txtenddt.Text
expenddt_1 = enddt_2.AddDays(-1)
enddt = enddt_2.ToString("dd/MM/yyyy")

enddt is a Date variable and when i convert enddt_2 to a string i get the error as

Conversion from string "17/01/2012" to type 'Date' is not valid.

Let me clarify, if a value in textbox is 17/01/2012 than after parsing the value is changed to 01/17/2012 (my systems Region and Language are dd/MM/yyyy) in enddt_2 and when i try to convert to dd/MM/yyyy format and store into a date variable i get the above error. This error comes only for the dates after 12. i.e a date variable accepts a date in MM/dd/yyyy format.The dates before 12 work fine, i.e for all dates from 1 to 12 there is no error.

How can i make enddt store the date in dd/MM/yyyy format.

Upvotes: 0

Views: 2996

Answers (2)

John Woo
John Woo

Reputation: 263723

did you try this?

Dim enddt_2 As Date = DateTime.ParseExact("17/01/2012", "dd/MM/yyyy", _
                      System.Globalization.CultureInfo.InvariantCulture)
Dim newD As Date = enddt_2.AddDays(-1)

Dim xStr As String = "Original Date: " & enddt_2.ToString("dd/MM/yyyy") & vbCrLf
xStr &= "FormatedOriginalDate: " & enddt_2.ToString("MM/dd/yyyy") & vbCrLf
xStr &= "NewDate: " & newD.ToString("MM/dd/yyyy")
Console.Writeline(xStr)

Output:

Original Date:         17/01/2012
FormatedOriginalDate:  01/17/2012
NewDate:               01/16/2012

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94645

The enddt is Date variable and you can't assign string value in it and do not change your regional settings or even date/time format.

Change type of enddt if you want to store string date.

 Dim enddt as String = enddt_2.ToString("dd/MM/yyyy")

Upvotes: 1

Related Questions