date to string formatting

obscuregirl

Member
Joined
Sep 13, 2006
Messages
15
Location
UK
Programming Experience
Beginner
Hi
I'm using DateTime.TryParseExact to verify dates that users put into a textbox (I know datepickers are better, but my users refuse to use them!).
In one particular instance, I have a start date text box, an end date text box and a duration (months) numeric field. When the user has entered a start date and a duration, I want to be able to calculate the end date.

I am using this code:

VB.NET:
Dim tempStartDate As Date
        Dim tempEndDate As Date
        Dim okDate As Boolean
       
        okDate = DateTime.TryParseExact(txtRGStartDt.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, tempStartDate)
        tempEndDate = DateAdd(DateInterval.Month, nuDuration.Value, tempStartDate.Date)
        txtRGEndDt.Text  = tempEndDate.ToString("dd\MM\yyyy")

The trouble is, the end date text is coming out all screwy e.g. if start date is 15/05/2005 and duration (months) is set to 1, end date is being set as '15M6y2005'.

I think it's to do with the fact that even though I am specifying a format of 'dd/MM/yyyy' for the TryParseExact function, the date it returns (tempStartDate) is in the format 'MM/dd/yyyy', so when I use the toString function and specify the 'dd/MM/yyyy' format, it doesn't like it!

Please does anyone know how to resolve this? Thanks.
 
I've just been given the answer on another forum. For anyone that's interested, here it is.....

You've got your delimiters the wrong way around so they're actually escaping the following character. This:
visual basic code:tempEndDate.ToString("dd\MM\yyyy")​
should be this:
visual basic code:tempEndDate.ToString("dd/MM/yyyy")​
or, if you actually do want backslashes it should be this:
visual basic code:tempEndDate.ToString("dd\\MM\\yyyy")​
Also, use the members of the Date object itself instead of DateAdd, e.g.
visual basic code:tempEndDate = tempStartDate.Date.AddMonths(Convert.ToInt32(nuDuration.Value))​
My thanks to the ever helpful jmcilhinney for this answer.​
 
Back
Top