简体   繁体   中英

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. ie a date variable accepts a date in MM/dd/yyyy format.The dates before 12 work fine, ie for all dates from 1 to 12 there is no error.

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

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM