Formatting a date,
In VB6 I could specify the a date that was so many days from today and change the format of the output in a nice and easy statement: Format(Now - 1, "yyyyMMdd"). I am trying to learn vb2010 and am getting an error on that statement: Operator '-' is not defined for types Date and Integer. Any idea on what the 2010 version of this simple VB6 statement?


The first parameter is the interval and you can specify other values for month, year, etc.

In VB6, the Date type would automagically convert back and forth to a floating-point number, with the integer part representing the day, and the fractional part representing the part of the day (hours, minutes, etc.). When you subtracted a number from a date, you were relying on this behaviour. Pushing this through Format to then converting back to a date, is a very slow way to go. In VB.Net, this conversion is no longer available.

Look at the DateAdd function in VB.Net; it is also available in VB6. To subtract a certain number of days, just add a negative number of days. The code below adds negative one days (which subtracts one day) from the old date (dteOld) to give the new date (dteNew). Look at the help on the Date type for more information on using the built-in date functions.
dteNew = DateAdd("d", -1, dteOld)

Edited 4 Years Ago by Nutster: Expand my explaination; fix spelling.

Thanks for the info. Unfortunate that doesn't do the conversion any longer, but I get the efficiency factor. We have files that are named in a specific way that corresponds to the date they were created. I am looking to somehow programmatically access these files. Is there some way to convert the date to string so it can be manipulated. I remember vb6 could convert strings and numbers and so on.

I recommend using the supplied enums like DateInterval.Day. You can run into confusion when using the older string ("D", etc) designation. For example, does "M" mean minutes or months?

Format can still be used to format your date as a string, just use the DateAdd function to do this.
Format(DateAdd(DateInterval.Day, -1, Now()), "yyyyMMdd")
You also might want to look at the built-in conversions of Date.toString. Look in the help under Standard Date and Time format Strings.

I am still new to VB.Net specifically, so did not think of the DateInterval constants. I agree, this is the clearer way to go.

Nutster, that worked perfectly and was exactly what I was looking for. The result was a string so I am able to add to it where I need to. Thanks

This question has already been answered. Start a new discussion instead.