Reputation: 13
In my code AddDays(1)
is working correctly for all days except the last day of the month.
I have a datatable containing data read in from a csv. Each row contains a date as string in format yyyy-mm-dd
. I want to add a day this date.
The code below is working for all dates where the day is not the last day of the month, but fails to increment the month otherwise.
Example:
2019-07-30
correctly increments to 2019-07-31
, but 2019-07-31
increments to 2019-07-01
rather than to 2019-08-01
.
I've tried Date.Parse
, and tried using System.Globalization.CultureInfo.InvariantCulture
or System.Globalization.DateTimeFormatInfo.InvariantInfo
without success.
MS documentation says
The AddDays method takes into account leap years and the number of days in a month when performing date arithmetic.
What am I doing wrong?
Dim enUK As New System.Globalization.CultureInfo("en-UK")
For Each row As DataRow In Outs.Select
Dim Lastdate As Date = DateTime.ParseExact(row("EndDate"), "yyyy-mm-dd", enUK)
Dim DepDate As Date = Lastdate.AddDays(1)
row("Date") = DepDate.ToString("yyyy-mm-dd")
Next
I expect the value of row("Date")
to be 2019-08-01
for a row("EndDate")
value of 2019-07-31
, rather than the value I'm getting of 2019-07-01
.
Upvotes: 1
Views: 332
Reputation: 1503449
You're using mm
in your format string, which means minutes rather than months. So you're not parsing the date correctly to start with. You want something like:
Dim enUK As New System.Globalization.CultureInfo("en-UK")
For Each row As DataRow In Outs.Select
Dim Lastdate As Date = DateTime.ParseExact(row("EndDate"), "yyyy-MM-dd", enUK)
Dim DepDate As Date = Lastdate.AddDays(1)
row("Date") = DepDate.ToString("yyyy-MM-dd", enUK)
Next
Note that I've also added the enUK
argument to ToString
- otherwise if your current thread culture uses a different calendar system, you could get some very odd results.
Upvotes: 3