DateTime.ToString

  • Thread starter Thread starter Andre
  • Start date Start date
A

Andre

Hi,

I have a problem with my Date conversion and can't find a way to resolve
it.

Here's my code :
friday= DateTime.Now.AddDays((day - (day * 2 + 2)))
thursday= friday.AddDays(6)
friday= friday.ToString("d-M-yyyy")
thursday= thursday.ToString("d-M-yyyy")

friday = #7/9/2004 9:51:25 AM#
thursday = #7/15/2004 9:51:25 AM#

After the conversion friday become 9/7/2004 but whit the thursday
conversion i receive this error : System.InvalidCastException:
Cast from string "15-7-2004" to type 'Date' is not valid.

I can't find a way to make it work, maybe the conversion think that 15
is the month instead of the day, i don't know...

Thanks.
 
Andre,

The problem isn't with the date itself but with the container you are
putting it into.

Instead of re-using the "thursday" object you have already tacitly dimmed as
a date object (which is now trying to hold a string and thus the error) put
the converted date into a new variable:

Dim MyDateString As String = thursday.ToString("d-M-yyyy")

It is a much recommended practice to always define all of your objects
explicitly. You really should declare "Option Explicit" And "Option Strict"
at the beginning of your code. It will save you a lot of headache in the
long run.

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 
Thank you. My problem is solved !

S. Justin Gengo said:
Andre,

The problem isn't with the date itself but with the container you are
putting it into.

Instead of re-using the "thursday" object you have already tacitly dimmed as
a date object (which is now trying to hold a string and thus the error) put
the converted date into a new variable:

Dim MyDateString As String = thursday.ToString("d-M-yyyy")

It is a much recommended practice to always define all of your objects
explicitly. You really should declare "Option Explicit" And "Option Strict"
at the beginning of your code. It will save you a lot of headache in the
long run.

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 
Back
Top