开发者

How do I increment a date by 1 day in VB.NET

开发者 https://www.devze.com 2023-02-24 23:36 出处:网络
If I have a textbox1 and button1, where in textbox1 the dat开发者_Go百科e will display as 01-Apr-2011, I want to click on button and have the date in textbox1 increase by 1 day.

If I have a textbox1 and button1, where in textbox1 the dat开发者_Go百科e will display as 01-Apr-2011, I want to click on button and have the date in textbox1 increase by 1 day.

So, if textbox1s date is 01-Apr-2011 then in textbox1 after clicking the button, textbox1s date will be 02-Apr-2011, a further click will get 03-Apr-2011 and so on.

How do I do this using VB.NET?


First you use DateTime.ParseExact to get the corresponding date-time instance and then use DateTime.AddDays to add the day and then format the date-time object to string again. For example,

Dim currentDate as DateTime
currentDate = DateTime.ParseExact(textbox1.Text, "dd-MMM-yyyy", null);
currentDate.AddDays(1)
textBox1.Text = currentDate.ToString("dd-MMM-yyyy")


Assuming that the control is called textbox1 your click handler needs to do something like this:

Dim currentDate as DateTime
' Get the current date from the textbox
currentDate = Convert.ToDate(textbox1.Text)
' Add one day
currentDate = currentDate.AddDays(1)
' Write the date back to the textbox
textBox1.Text = currentDate.ToString("dd-MMM-yyyy")

Note: The exact format of the date written back to textbox1 may not match precisely what you're after - you'll almost certainly want to use DateTime.ToString and choose an appropriate format pattern.


Something extra that I just had to use and is quite obvious, but to minus 1 day from a date in VB.NET you would do the following:

myDate = Mydate.AddDays(-1)


different ways to add one day to a datetime object

 Dim dt as DateTime(2011,10,12)
    dt = dt.AddDays(1)
    dt = dt.AddHours(24)
    dt = dt.AddMinutes(1440)
    dt = dt.AddSeconds(86400)

result will be 16 that is 12 + 4 days

0

精彩评论

暂无评论...
验证码 换一张
取 消