VMS
VMS

Reputation: 403

Converting a day and a year to a date in VBScript

I've seen a few similar questions/answers, but none of them answered my question/answered for VBS. I have a set of days that I would like to convert to dates for this year. However, when I try to convert them to dates, I get the wrong values because it uses the year 1900. Is there some way I can specify the year in the CDate function? I looked at the Calendar class, but that didn't apply because I'm using VBScript.

MsgBox(CDate(195))
MsgBox(CDate(196))
MsgBox(CDate(197))
MsgBox(CDate(198))
MsgBox(CDate(199))

These give me 7/13/1900, 7/14/1900, 7/15/1900, etc.

Upvotes: 0

Views: 1276

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Use DateAdd to add a number of days to a start date obtained by DateSerial:

>> dt2014 = DateSerial(2014, 1, 1)
>> WScript.Echo dt2014
>>
01.01.2014
>> WScript.Echo DateAdd("d", 195, dt2014)
>>
15.07.2014

(German locale; lookout for a +-1 bias (adding to the first day of year))

Update wrt to @Bond's comment:

Even if you need to add many days to on start date (as I understood the task), using just DateSerial with many different day-parameters may well be more efficient.

Upvotes: 3

Related Questions