How to compare dateformat rather than using of time - vb.net

How can I compare the last characters using of month, day, and year or the completedate rather than using datetime, Example case is Textbox3 is greater than textbox9 because Textbox3 day = 26 and textbox9 day = 25.
Mycode:
'in my case I have 2 Textbox.
'Date format: hh.mm MM/DD/YYYY
'Textbox3= 02.02 03/26/2014
'TextBox9= 21.01 03/25/2014
If Val(Strings.Left(TextBox9.Text.Trim, 5)) < Val(Strings.Left(Textbox3 .Text.Trim, 5))Then
TimeError.ShowDialog()
End If

Really, the fastest, most reliable, and most effective way to do this is to parse the values into a DateTime. And taking a step back from there, the fastest, most effective way to get a date time from a textbox is to use a DateTimePicker control.
But if that's not an option, we can build on the code I gave you last time:
Dim temp1() As String = Textbox3.Text.Trim().Split(" .".ToCharArray())
Dim temp2() As String = Textbox9.Text.Trim().Split(" .".ToCharArray())
If DateTime.Parse(temp2(2)) < DateTime.Parse(temp1(2)) Then
TimeError.ShowDialog()
End If
I'll add that you probably want to also have code to compare the time values in the case where the date portions are equal. Given this as a starting point, you should be able to write that code on your own.

in vb.net you can comopare dates like this:
dim date1 as date = cdate(Textbox1.text)
dim date2 as date = Date.now()
if date1.date=date2.date then ....
and months like this
if date1.month=date2.month then ...

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")

How to change date format vb.net 2015

I want to filter SQL-table between start date and end date, I used before string variable then I use string.format to make the format mm/dd/yyyy, I tried now in VB.net 2015 the following code:
Dim S as String
s=inputbox("Enter Start date")
S=string.format(S,"mm/dd/yyyy")
But it doesn't work, can somebody give me a solution?
You could try this for handling the input value, assuming you only need the date value as a formatted string, since your question is about formatting a date:
Dim S As String
S = InputBox("Enter Start date")
If IsDate(S) = True Then
Dim d As Date = Date.Parse(S)
S = d.ToString("mm/dd/yyyy")
Else
'Handle the non date input here
End If
But I think you should consider #Plutonix comment, since we don't know exactly how you are sending the date to perform the filtering, or how your table fields are defined.
Regards!

VB.net How to Compare difference in years

New VB coder here, trying to check if todays date is more then 10 years past a date from a grabbed database entry, and display a message if it is.
The Database is already imported and set up in the VB application H ave made, and working, I made a report to display the information.
I am guessing I need to use the Datediff but I can't seem to get it to work, Thanks.
I will give my variable name here
Dim Custsince as Date
'From the Database here
CustSince = CustListodr("Custsince")
Thanks in advance, working with dates is not my strong point.
You can just use a TimeSpan directly by subtracting the dates:
Dim customerLength = DateTime.Now - Custsince
Dim approxYears = customerLength.TotalDays / 365
If the date read from the database is already stored in a Date variable, you can simply subtract one date from another to get the difference. The result of subtracting two dates is a TimeSpan object. TimeSpan objects contain useful properties that allow you to see how long the span of time is in various units (e.g. days, hours, minutes). For instance:
Dim date1 As Date = ...
Dim date2 As Date = Date.Now
Dim span As TimeSpan = date2 - date1
If span.TotalDays >= 3650 then ' Ten years
'...
End If
Alternatively, if you need to compare calendar years, rather than the actual span of time, you can compare the years from each date, like this:
If date2.Year - date1.Year >= 10 Then
'...
End If
If the date being read from the database is stored as a string, rather than as a Date value, you would need to use Date.Parse or Date.ParseExact to convert the string into a Date value.

VB.Net 2005, how can I subtract a date from the (current date minus 7 days) and produce a number of days?

I have a date in the future e.g. 13/10/2008 I need to subtract the current date (today is the 28/09/2010) minus 7 days, so thats 21/09/2010 minus 13/10/2008, which would equal erm, 720 something ?
But the current date won't always be 28/09/2010, obviously.
I need the code for this.
EDIT: When i said future I mean past :)
Sub Main()
Dim dt As DateTime = New DateTime(2008, 10, 13)
' be careful what you are subtracting from what
' the date you have is not in the future (year 2008)
' if the date is in the future: (dt.Subtract(DateTime.Now.AddDays(-7))).TotalDays
' or simply take the absolute value
Dim days As Double = (DateTime.Now.AddDays(-7).Subtract(dt)).TotalDays
Console.WriteLine(days)
End Sub
You will also notice that the TotalDays property is of type Double.
13/10/2008 is not exactly in the future :)
Sorry for using C# code, but:
(dateInFuture - DateTime.Now.AddDays(-7)).TotalDays
Should work. Of course the other way around if you mean in the past:
(DateTime.Now.AddDays(-7) - dateInPast).TotalDays
Dim ValidDate As Date =cDate("Tuesday, December 31, 2013") 'A date in Future
Dim date1 As New System.DateTime(ValidDate.Year, ValidDate.Month, ValidDate.Day)
Dim date2 = Now
Dim Diff1 As System.TimeSpan
Diff1 = date1.Subtract(date2)
Dim TotRemDays = (Int(Diff1.TotalDays))
MsgBox(TotRemDays)
"I need the code for this" seems a bit too much like "Plz give meh teh codez", and your "date in the future" seems a little bit in the past.
Anyway, you should investigate the relevant methods of the DateTime structure, in particular the Subtract method (both overloads, or in alternative its subtraction operator), and you should have a look at the TimeSpan structure too.
You could create a DateTime for the date of today, subtract a TimeSpan of 7 days to it, and then subtract such result to a DateTime representing your date in the future (or, if it is in the past, do the opposite). You'll get a TimeSpan representing the difference in time between the two dates, from which you can easily get the number of days using its Days property.
As other said, to do the first subtraction you can also use the AddDays method of the DateTime structure.

How would I find the closest valid date to one given as an invalid date string?

This issue stems from an accounting package that spits out text-based reports with rows of data having invalid dates, like February 31st or September 31st.
The reports are formatted with spaces and mono-spaced fonts. My goal is to parse out the data needed and generate a more formal report (SSRS).
What I am interested in fixing is the situation where a date is invalid and can't be directly converted into a DateTime struct. The date format from the report is MMM-dd-yy (e.g. Feb-30-10). I would like to convert the invalid date strings into the closest valid DateTime in the same month before showing them in the formal report. I've seen this done two ways in my time as a developer, both very poorly, so I want to come up with a simple way of doing it (if there isn't a built-in way I don't know about).
The first bad method I've seen(I can't believe I'm even showing you!):
Dim month As Integer = <Parse out the month from the bad date string>
Dim day As Integer = <Parse out the day from the bad date string>
Dim year As Integer = <Parse out the year from the bad date string>
Dim validDate As DateTime
While True
Try
validDate = New DateTime(year, month, day)
Exit While
Catch ex As ArgumentOutOfRangeException
day -= 1
End Try
End While
I hope I don't have to explain what I don't like about that method.
The second bad method:
Dim badDateString As String = <Current date string from text report>
Dim validDate As DateTime
If DateTime.TryParseExact(badDateString, "MMM-dd-yy", Nothing, Globalization.DateTimeStyles.None, validDate) Then
Return validDate
End If
badDateString = badDateString.Replace("31", "30")
' ... try the parse again, if still not valid, replace "30" with "29"
' ... try the parse again, if still not valid, replace "29" with "28"
These make for some sad code and me a sad developer.
I've been trying to think of a more efficient way of doing this. Any ideas?
EDIT:
I found a solution and have posted it, but I liked Guffa's answer more.
Reading the previous code, the last code is pretty much what I was going to suggest.
Here is a variation of the code:
Return New DateTime(year, month, Math.Min(day, DateTime.DaysInMonth(year, month)))
Here was the solution I discovered before Guffa answered. It takes the parts of a date (month, day, year), uses the number of days in that particular month/year combination to validate the incoming day part, and adjusts if necessary before constructing a new DateTime.
Dim validDate As DateTime
Dim dayMax As Integer = DateTime.DaysInMonth(year, month)
Dim newDay = day
If day > dayMax OrElse day < 1 Then
newDay = dayMax
End If
validDate = new DateTime(year, month, newDay)
Return validDate