DateAdd function to add months - vb.net

I used this code to add months
dtExpiry = DateAdd(DateInterval.Month, intDuration, dtStartDate)
and I also tried this code,
dtExpiry = DateAdd("m", bytDuration, dtMemStartDate)
but every time it just adds Days not months. The date format has to be dd/mm/yyyy. I've changed my PC date format to dd/mm/yyyy but still it keeps adding Days instead of Months.
BTW I'm receiving the duration and startDate from the Main calling program which extract these values from a data file thats in CSV format.

Your code looks ok, but you may have an incorrect data type.
Try this and see if this works:
dtExpiry = DateAdd(DateInterval.Month, intDuration, CDate(dtStartDate))
If that works then check the data type of dtStartDate.
All this can be avoided if you switch Option Strict On, as the code won't compile if dtStartDate is not of type DateTime
Note that you should also be able to do this:
dtexpiry = dtStartDate.AddMonths(intDuration)
This will fail to compile even with Option Strict Off if dtStartDate is not a DateTime so could be a safer option.

Use datetime.tryparse to convert your string to a date, then use as below?
You can also specify a conversion and specifically tell it what is where in the string (m/d/y)
I.e.:
Dim mydate As New Date
mydate = DateTime.ParseExact(datestring, "dd/MM/yyyy", Nothing, DateTimeStyles.NoCurrentDateDefault)
Dim secondDate As New Date
secondDate = mydate.AddMonths(6)
Or am I missing your question?

Related

VB.NET - Unable to enforce two digit day and month when converting string to Date

I am having difficulty taking a string and converting it to a vb.net Date object, while enforcing two digit day and month. Please consider the following form example, using today's date. (02/01/2019)
Dim myDate As Date = Date.Now
Dim myDateString = String.Format("{0:D2}/{1:D2}/{2:D4}", myDate.Month, myDate.Day, myDate.Year)
myDate = DateTime.ParseExact(myDateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None)
Label1.Text = myDate 'This will show "2/1/2019"
Label2.Text = myDateString 'This will show "02/01/2019"
This situation leaves Label1.Text as "2/1/2019", but Label2.Text as "02/01/2019". No matter what I have tried, it appears that the actual conversion from the correctly formatted String into a Date object will remove these zeros. Does anyone have any thoughts as to how I can enforce a "MM/dd/yyyy" format when converting to a Date object?
Thank you in advance,
You should consider that a DateTime variable has no format. It is just a number expressing the Ticks elapsed from the starting DateTime.MinValue (1/1/0001).
It has no memory that you have built it using a particular formatting parser.
So, when you assign a date to a string like you do in your
Label1.Text = myDate
then you are asking the ToString representation of that date. The output of this method without a formatting parameter is whatever your locale settings decide it to be. If you want to force the desidered output you need to tell the date's ToString method in what format you want the output
Label1.Text = myDate.ToString("MM/dd/yyyy")

changing date fromat from mm/dd/yyyy to dd/mm/yyyy VBA

So I know this question has been asked a couple of times over, but I believe my situation is a bit different (happy to be proven wrong of course!)
Here is the data flow: a user types a date in a date in a form. They then click a button. My macro then takes that date, runs it through the following function:
Function AddWeekDays(StartDate As Long, Days As Long) As Date
Dim i As Long
Dim d As Date
d = StartDate
i = 0
While i < Days
d = DateSerial(Year(d), Month(d), Day(d) + 1)
If Weekday(d, vbMonday) < 6 Then
i = i + 1
End If
Wend
AddWeekDays = d
End Function
Then it formats the date to change it from mm/dd/yyyy to dd/mm/yyyy in the following way:
Dim deadline As Date
Dim deadline_formatted As Date
Dim DateReceived As String
Dim DateConverted As Date
DateReceived = txt_DateReceived.Text
DateConverted = Format(DateReceived, "dd/mm/yyyy")
deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline_formatted = Format(deadline, "dd/mm/yyyy")
However, the deadline_formatted value is still coming out in the mm/dd/yyyy format.
As an example, when a user enters 01/05/2017 the program should return deadline_formatted = 12/05/2017, but it returns deadline_formatted = 05/12/2017
I have tried changing the variable type to string to see if that made a difference (it didn't), and have tried directly converting the deadline variable to the required format by using the following code:
deadline = Format(AddWeekDays(DateValue((CStr(DateConverted))), 9),"dd/mm/yyyy")
which still returns the incorrect format.
Can anybody out there suggest either:
How to fix the formatting issue to get the deadline_formatted into the format dd/mm/yyyy
OR
suggest a "workaround" to flip the "dd" with the "mm" (not ideal obviously, but if it works, it works!)
Thanks for any advice!
The best way to solve this issue is to actually change your computer's default date/time format to match the method used by the users. (In comments it is stated that the users are Australians but your company is US-based, so the default is probably currently set to be the USA's "mm/dd/yyyy" format.)
By ensuring that the computers date/time format is correct, it will allow you to process a date as a Date, and it can be stored in Excel cells as a Date, which then allows any of the Australian users to see it displayed as "dd/mm/yyyy" format while a USA-based colleague would see it displayed as "mm/dd/yyyy".
There is a financial risk to your company caused by forcing users to interact with software using an unfamiliar date system, as accidental entering of dates in the wrong formats can lead to major errors downstream, so it is in the company's best interest to allow you to change the settings to be relevant to the users.
It is not directly related to your problem, however I believe it might fix your issues. The manual calculation of adding week days might be the problem here.
There is a built in function to add workdays. You can include/exclude weekends/holidays. The following code replaces your above mentioned code.
Sub AddWeekDays()
Dim deadline As Date, deadline_formatted As Date
deadline = txt_DateReceived.Value
deadline_formatted = Format(Application.WorksheetFunction.WorkDay(deadline, 9), "dd/mm/yyyy")
'debug.print deadline_formatted
End Sub
the result to be String.
Dim deadline As Date
Dim deadline_formatted As String '<~~ change string
Dim DateReceived As String
Dim DateConverted As Date
txt_DateReceived = "01/05/2017"
DateReceived = txt_DateReceived
DateConverted = Format(DateReceived, "dd/mm/yyyy")
'deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline = AddWeekDays(CLng(DateConverted), 9) '<~~ change Long
deadline_formatted = Format(deadline, "dd/mm/yyyy")
I wouldn't bother about the regional settings. Instead, make sure that all dates are captured as Date() or Now() values (42123 or 42123.5555). On the output side such values can be presented in any format you wish.
To ensure that dates are entered correctly my preferred way is to use a date picker. If that can't be done make no rules for entering the date at all, working on the presumption that each user will know how to enter a date on his/her machine. Add a date check, like ISDATE(), which will catch some input errors but not all. You don't need to catch all. You only need to teach users how to input dates on their respective PCs.
With this line you don't need anything else.
Range("E:E").TextToColumns FieldInfo:=Array(0, xlDMYFormat)
'1.2.2019 -> 01/02/2019
'2,3,2019 -> 02/03/2019
'3-4-2019 -> 03/04/2019
'4*5*2019 -> 04/05/2019
'5_-6-*2019 -> 05/06/2019
'and so on
Of course you can change the format with
xlMDYFormat

How do I format a date in a string variable to year date month in vb.net

I have a date in string variable strOrderEndDate which looks like this 8/14/2015.
I would like to convert it to 2015-08-14.
How do I do this in vb.net?
I tried strOrderEndDate.ToString(yyyy mmmm dd) but its not working
As the comments indicate, you first need to convert the string to a date using CDate. Then you can use the .ToString method on the new date type variable to format the output as desired:
Dim strOrderEndDate As String = "8/14/2015"
Dim datOrderEndDate As Date = CDate(strOrderEndDate)
MsgBox(datOrderEndDate.ToString("yyyy-MM-dd"))
...or as Plutonix recommends, you can use DateTime.Parse to perform the conversion. He's pretty smart so if he says it's better, then it's better.
Dim datOrderEndDate As Date = DateTime.Parse(strOrderEndDate)

Error: Date Type Conversion from String in VB .Net

For the following code, I am receiving this error: "Conversion from String "10/22.2014 12:00:00 A10" to type 'Date' is not valid." Note - in comparison to the code, below - the error message's conversion of AM to A10.
What I Am Trying To Do
I am trying to give a user the ability to query a database for transactions that occurred, today. In order to do this, I need to specify the timestamp for the transaction, i.e. MM/dd/yyyy timestamp. I have consulted the MSDN documentation; however, am unable to get my code to function, properly.
By default, Date objects appear to drop their timestamp (this may be a result of the code I am working with, e.g. the casting); therefore, when specifying a date range of "today" (Today's Data - Today's Date), I am left with the default behaviour of the object: Today's Date 12:00:00 AM - Today's Date 12:00:00 AM. Regardless as to why this is happening, this is the problem with which I am left.
The objective: MM/dd/yyyy 12:00:00 AM - MM/dd/yy 11:59:59 PM (the day being the same).
My goal is to force a particular timestamp for a Date object (note this is not a DateTime object). By specifyiong the time range, I am able to grab all data from a database for today.
What I've Got
Below, is the code and, below that, the description (I've tried to condense the code as much as possible). You'll also note that this is only half of the code, i.e. the FromDate portion (presumably the format can be replicated for the ToDate:
Public Shared Function ToFromDate(ByVal aValue As Object) As Date
Dim Result As Date
Try
Result = CDate(aValue)
Catch ex As Exception
Result = Now
End Try
Result = CDate(String.Format("{0:MM/dd/yyyy 12:00:00 AM}", Result))
Return Result
End Function
The above code takes as an argument a DateTime, e.g. 10\10\2010 12:15:63 PM (and, for the purposes of my problem, the timestamp is included). Again, I am trying to take that Date with timestamp and change the time. Result receives aValue, casting the object as Date to "ensure" it is a date.
After Result receives a value (as when declaring a Date it is initialized to #12:00:00 AM#, interestingly enough), I attempt to CDate() a formatted String object. I have also attempted to remove the second cast, yet still receive the same error (the Result = CDate(String...) line throwing the error).
Question(s)
The main question: how do I appropriately cast a date to include a specified time?
The second, trivial question: what's with the # surrounding the Date? Is this a SQL 'thing'?
Here's my work around for the above not working, so far:
Dim Result As Date
Dim DateString As String = CStr(aValue)
Dim TestDateString As String = DateString.Substring(0, DateString.IndexOf("/"))
Dim NewDateString As String = ""
If TestDateString.Length = 2 Then
NewDateString = DateString.Substring(0, 10)
Else
NewDateString = DateString.Substring(0, 8)
End If
NewDateString = NewDateString + " 12:00:00 AM"
NewDateString = CObj("#" + NewDateString + "#")
Result = CDate(NewDateString)
Return Result
First, a date is the number of ticks since a point in time. Formatting it to a string and then converting to a date does nothing but spin the wheels of your CPU.
Because of culture issues, you should always create dates using NEW DATE(?,?,?,etc)
Second, the # is a vb6 way of creating dates (and MS Access) that is there for backwards compatibility.
Third, If you have a date (no time or as of midnight), and you want it to be as of say 6AM, you simply add the time you want. IE:
Dim d As Date = New Date(2014,1,1)
d = d.AddHours(6)
'Result: d = 1/1/2014 6:00:00 AM
Lastly, if you have a date and time and you want to remove the time, there are many ways but this is the one I like:
Dim d As Date = Now
d = New Date(d.Year, d.Month, d.Day)

Convert string date to show 2 year digits

i have a string which has a value of "08-06-2008". I want the result to look like "08-06-08". Is there a way to do this? I've tried CDate but that only gives me 8/06/2008 which doesnt resolve the issue.
Parse it to Date and back to string:
Dim dt As Date = Date.ParseExact("08-06-2008", "MM-dd-yyyy", CultureInfo.InvariantCulture)
Dim result As String = dt.ToString("MM-dd-yy", CultureInfo.InvariantCulture)
Since that is a normal format you could also omit the format string and use Date.Parse directly:
Dim dt As Date = Date.Parse("08-06-2008", CultureInfo.InvariantCulture)
I have used CultureInfo.InvariantCulture to avoid localization issues, normally your current culture is used in Parse/ParseExact and ToString.
See: Custom Date and Time Format Strings
Firstly, avoid CDate. It is a hangover from VB6, and is almost certainly less efficient than using the .net equivalent.
The following should give you the right answer:
string value = DateTime.ParseExact("08-06-2008", "dd-MM-yyyy").ToString("dd-MM-yy")
Note that your existing date format is ambiguous, so I've been unable to tell if you're meaning the 6th of August or the 8th of June - this is why I've used ParseExact over Parse. ParseExact is also slightly more efficient, as it tells the framework which format to use, rather than it having to guess.
Try this
Dim FormatString As String = ""
Dim SampleDate As DateTime
SampleDate = Now()
FormatString = Format(SampleDate,"dd-MM-yy")