Stephen Gellman
Stephen Gellman

Reputation: 21

vb.net add days to a date

Dim DespatchDate As DateTime
Dim ReceiptDate As DateTime 

DespatchDate = #3/7/2017 12:00:00 AM#  'I am in the UK so this is 3rd July 2017

ReceiptDate = DespatchDate.AddDays(60)   'Returns #5/6/2017 12:00:00 AM#

I would expect "1/9/2017" the 1st September 2017

I also tried

ReceiptDate = DateAdd("d", 10, DespatchDate)  which returned #3/17/2017 12:00:00 AM#

I must be doing something wrong but what?

Upvotes: 2

Views: 21997

Answers (1)

Fabulous
Fabulous

Reputation: 2423

The date literal in VB uses the US format regardless of where you are. Your code:

DespatchDate = #3/7/2017 12:00:00 AM#  'I am in the UK so this is 3rd July 2017

is creating the date March 7 2017. Read more on date literals or use the constructor on the date class that makes it more apparent what you are doing.

Update In order to be sure what the date is and to avoid ambiguity, you can define it this way:

DespatchDate = New Date(2017, 7, 3)   ' Without the time of day, 12AM is implied
DespatchDate = New Date(2017, 7, 3, 12, 34, 56) ' July 3 2017 12:34:56 PM

The good thing with this is you can see from intellisense while typing the code what each number means. And if someone else had written the code, you can invoke intellisense to see what each argument means. As you can see from what I highlighted in my screenshot, the time is in 24 hour format.

Screenshot of what you will see from intellisense

Upvotes: 4

Related Questions