0
votes

I am using the following function to Convert a String variable to a Date. Subtract a day from it and convert the date back to a String. The code goes as follows

Dim edate As String
Dim expenddt As Date

edate = txtenddt.Text
expenddt = Date.ParseExact(edate, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
expenddt = expenddt.AddDays(-1)

Dim asd As String = expenddt.ToString

If edate has a value 29/12/2011 than the value in expenddt gets changed to a different format and the value in expenddt comes to 12/29/2011 and later after subtracting a day expenddt is 12/28/2011 and than when i convert it back to a String i get the value in asd as "12/28/2012 12:00:00 AM"

I have changed the date format on my system to d/M/yyyy in Regional And Language Option in Control Panel but i still get a different format in expenddt

Can anyone explain me why this is happening? How can i keep the format of the date in dd/mm/yyyy e.g 29/12/2011 and after Subtracting a day it should remain 28/12/2011 and not 12/29/2011

2
I can't explain why (it should be using the format set via Control Panel), but why don't you just specify the format when you call ToString? - andygjp
@andygjp . That i never thaught of.Thank you so much. Actually im new to vb, i know how we do it in C# .Can you please tell me how to Specify a format? is it .ToString("dd/mm/yyyy")? - Ishan
@andygjp That actually solved my question. - Ishan

2 Answers

2
votes

Use Date.ToString() to convert date to string with dd/MM/yyyy format.

Dim asd As String = expenddt.ToString("dd/MM/yyyy")
0
votes

Just try this:

Dim dateString As String = "Mon 16 Jun 8:30 AM 2008"
Dim format As String = "ddd dd MMM h:mm tt yyyy"
Dim dateTime__1 As DateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture)

hope this may helpful....