I want to compare two times in VB.net:
I have 1:42:21 PM and I want it to compare with TimeOfDay in VB.net how can I do that?
New DateTime(1, 1, 1, 13, 42, 21) > TimeOfDay
Or you can enclose a DateTime expression in # signs:
TimeOfDay > #1:42:21 PM#
Show the time difference in hours, minutes and seconds
Dim TimeEnd As DateTime = #5:00:00 PM#
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim span As System.TimeSpan = TimeEnd.TimeOfDay - DateTime.Now.TimeOfDay
Label1.Text = span.Hours & "hr:" & span.Minutes & "min:" & span.Seconds & "sec"
End Sub
You'd work out the format of your input time, and then call the ToString() method on your vb.net object, putting the same format in.
So for example, if your input format is h:mm:ss tt as it appears to be in your case, one method would be to do:
Dim compareTime As String = "1:42:21 PM"
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
' The times match
End If
If you want to do some kind of comparison, you should use the DateTime.Parse() function to convert your input date into a DateTime object. Then you can simply use the > or < signs:
Dim myCompareTime As DateTime = DateTime.Parse("1:42:21 PM")
If myCompareTime.TimeOfDay > DateTime.Now.TimeOfDay Then
' Compare date is in the future!
End If
The following sample function can be used to compare time
Function comTime()
Dim t1 As Integer = DateTime.Now.TimeOfDay.Milliseconds
Dim t2 As Integer = DateTime.Now.AddHours(1).Millisecond
If (t1 > t2) Then
MessageBox.Show("t1>t2")
ElseIf (t1 = t2) Then
MessageBox.Show("t1=t2")
Else
MessageBox.Show("t2>t1")
End If
End Function
is it something along the lines of this that you are looking for?
To compare the time portion of two DateTime values:
Dim TimeStart as DateTime = #1:42:21 PM#
Dim TimeEnd as DateTime = #2:00:00 PM#
If TimeStart.TimeOfDay < TimeEnd.TimeOfDay Then
Console.WriteLine("TimeStart is before TimeEnd")
End If
Dim MyDate As DateTime = Convert.ToDateTime(MyDateAsString)
Dim MyFractionOfDay As Double = MyDate.TimeOfDay.TotalDays
The question is still valid in 2022. After extracting time as a fraction of day, it can be compared, or used to visualize progress through the day.
Related
I am trying to find the last day of the month and compare it to today's date
I do NOT want the integer number I would like the result in this format "MM-dd-yyyy"
Date Picker will not work for this project
Here is the code I using but the process seems overly complicated concocting strings
Side note when today is after the 4th Tue I write True and the Last Day of the month to a DB
when today is after the last day of the month and the bool is now True I write the new last day of the new month and false to the DB
Function FourthTueOfMonth(dt As Date) As Date
Dim currDate = New Date(dt.Year, dt.Month, 1)
Dim nTuesday = 0
While nTuesday < 4
If currDate.DayOfWeek = DayOfWeek.Tuesday Then
nTuesday += 1
End If
currDate = currDate.AddDays(1)
End While
Return New Date(dt.Year, dt.Month, currDate.Day - 1)
End Function
Private Sub btnFindDate_Click(sender As Object, e As EventArgs) Handles btnFindDate.Click
Dim tORf As Boolean = False
Dim dateToday = Date.Today
Dim dateFourthTue = (FourthTueOfMonth(Date.Today))
tbFourthTue.Text = dateFourthTue.ToString("MMM-dd-yyyy")
tbThree.Text = dateFourthTue.ToString("yyyy-MM-dd")
tbEndOFMonth.Text = Date.DaysInMonth(Date.Now.Year, Date.Now.AddMonths(0).Month).ToString
Dim dToday As Date
dToday = Date.Parse("10-01-2021")
Dim dtY = dateToday.ToString("yyyy")
Dim dtM = dateToday.ToString("MM")
Dim eom As String = Date.DaysInMonth(Date.Now.Year, Date.Now.AddMonths(0).Month).ToString
Dim dtALL As String
dtALL = dtM & "-" & eom & "-" + dtY
Dim testD As Date
testD = Date.Parse(dtALL)
If tORf = False And dToday > dateFourthTue Then
MessageBox.Show("Today > Fourth Tue")
'tORf = True'Write True
'tbMessage.Text = tORf.ToString
End If
If tORf = True And dToday > testD Then
MessageBox.Show("Today > End Of Last Month")
'tORf = False write False
'tbMessage.Text = tORf.ToString
End If
End Sub
The solution provided by #Albert D. Kallal is great for Visual Basic since DateSerial is in the Visual Basic namespace in the DateAndTime class. Here is a solution that should work in both vb and C#.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dtToday As Date = Date.Today
Dim dtEndOfMonth = New Date(dtToday.Year, dtToday.Month + 1, 1).AddDays(-1)
Debug.Print(dtToday.ToString)
Debug.Print(dtEndOfMonth.ToString("MM-dd-yyyy"))
End Sub
A few things:
You want to use today - not "now()" as that includes a time portion. While a date type only has date, you should consider if you have datetime, and either way, no need to introduce and use a value that includes both date and time such as now does.
I reocmmend this code:
Dim dtToday As Date = Date.Today
Dim dtEndOfMonth As Date = DateSerial(dtToday.Year, dtToday.Month + 1, 0)
Debug.Print(dtToday)
Debug.Print(dtEndOfMonth)
Output:
Today happens to be the 1st, but any date would work. This includes end of year, and even leap years.
2021-10-01
2021-10-31
So, this is a long time old trick - goes back to old VB6, and even old VBA code from 20 years ago.
So, we use date serial to produce a date, but if you use 0 for the day, then you get the previous day, and thus gets you the last day of the current month.
So we toss in year, month + 1, and 0 for the date - that results in the last day of the current month.
I hate to admit I might have gave up the search too quick
found the answer here
Answer Here
Here is the code
Dim dateToday = Date.Now.AddMonths(0)
Dim dateEndOfMonth = New Date(dateToday.Year, dateToday.Month, DateTime.DaysInMonth(dateToday.Year, dateToday.Month))
tbMsg.Text = dateEndOfMonth.ToString("MM-dd-yyyy")
Code seems to be working ?
I have seen suggestions to use this format for comparing dates
TEST DATES use this format yyyyMMdd Please comment if you can add to the answer
I am needing some help converting a function from access vba to vb.net.
The script generates a new date, based on the date entered, and the number of months to be added.
“If today is the second Tuesday in March, what will be the second Tuesday in 4 months?”
Public Function NdNwk(dType As String, _
dtSpan As Integer, sDate As Date) As Variant
' This Function RETURNS the DAY of WHICH WEEK
' (e.g. Second Tuesday of the Month).
' FUNCTIONS to be passed to Variables:
' gtDoW: Day of the WEEK of the START DATE.
' (1 for Sunday, 2 for Monday, etc.)
' gtWoM: WEEK of the MONTH of the START DATE.
' (1 for First, 2 for Second, etc.)
' gtDSTdt: Desired DATE
' (generated by the [DateAdd] Function).
' CALL EXAMPLE: If TODAY is Tuesday, March 10, 2020,
‘ (second Tuesday of March), then using
' NdNwk(m, 2, #5/21/2020#)
' Would generate the DATE 5/12/2020,
' As the SECOND TUESDAY of MAY.
Dim gtDSTdt As Date, gtWoM As Integer, gtDoW As Integer
Dim iLoop As Integer, iPick As Integer, dstDTdom As Date
gtDoW = Weekday(sDate)
gtWoM = (Int((Day(sDate) - 1) / 7) + 1)
gtDSTdt = DateAdd(dType, dtSpan, sDate)
For iLoop = 1 To Day(DateSerial(Year(gtDSTdt), _
Month(gtDSTdt) + 1, 0))
dstDTdom = DateSerial(Year(gtDSTdt), _
Month(gtDSTdt), iLoop)
If Weekday(dstDTdom, 1) = gtDoW Then
iPick = iPick + 1
If iPick = gtWoM Then
NdNwk = dstDTdom
Exit Function
End If
End If
Next
End Function
Any and all help is appreciated here.
I used several of the properties and methods of the .net DateTime structure. https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netcore-3.1
The arithmetic in the Function used the Mod operator which returns the remainder of the division. The integer division (the formard slash \) returns the integer portion of the division.
The only other thing that might be unfamiliar is the interpolated string, a string starting with $"". This allows you to directly embed variables in the string surround by { }.
Private Function NdNwk(InputDate As Date, MonthsAhead As Integer) As String
Dim newDate As Date
Dim DofWeek = InputDate.DayOfWeek
Dim Day = InputDate.Day
Dim OfInputMonth As Integer
If Day Mod 7 = 0 Then
OfInputMonth = Day \ 7
Else
OfInputMonth = (Day \ 7) + 1
End If
Dim TempDate = InputDate.AddMonths(MonthsAhead)
Dim NewMonth = TempDate.Month
Dim NewYear = TempDate.Year
Dim FirstWeek As Date
Dim NewDay As Integer
For d = 1 To 7
FirstWeek = New Date(TempDate.Year, TempDate.Month, d)
If FirstWeek.DayOfWeek = DofWeek Then
NewDay = d
Exit For
End If
Next
Dim DaysToAdd = (OfInputMonth - 1) * 7
newDate = New Date(NewYear, NewMonth, NewDay).AddDays(DaysToAdd)
Dim NewDateString = $"{newDate.ToString("MM/dd/yyyy")} is the {GetOrdinalString(OfInputMonth)} {DofWeek} of {TempDate.ToString("MMMM")}, {TempDate.Year}"
Return NewDateString
End Function
Private Function GetOrdinalString(input As Integer) As String
Dim output As String
Select Case input
Case 1
output = "1St"
Case 2
output = "2nd"
Case 3
output = "3rd"
Case 4
output = "4th"
Case 5
output = "5th"
Case Else
output = ""
End Select
Return output
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim InputDate As Date
Dim MonthsToAdd As Integer
If Not Date.TryParse(TextBox1.Text, InputDate) Then
MessageBox.Show("Please enter a valid date in Date")
Return
End If
If Not Integer.TryParse(TextBox2.Text, MonthsToAdd) Then
MessageBox.Show("Please enter a valid number in Months To Add")
Return
End If
Dim d = NdNwk(InputDate, MonthsToAdd)
MessageBox.Show(d)
End Sub
First of all, thanks for all the feedback.
The solution that I was able to parse together is as follows:
A text box to show the number of months.
A text box to show the new date.
A button click action to run the following code:
Private Sub BtnMonth_Click(sender As Object, e As EventArgs) Handles BtnMonth.Click
Dim WrkDt As Date = Now
Dim QtyMnths As Integer = CType(TxtMntCount.Text, Int32)
Dim newFoM = New Date(WrkDt.Year, WrkDt.Month, 1).AddMonths(QtyMnths)
Dim DoWDt As Integer = WrkDt.DayOfWeek
Dim newMntdate = newFoM.AddDays(Enumerable.Range(0,
Date.DaysInMonth(newFoM.Year, newFoM.Month) - 1).Where(Function(i) newFoM.AddDays(i).DayOfWeek = DoWDt).Skip(1).First())
TxtNewDate.Text = Format(newMntdate, "MMMM dd, yyyy (ddd)")
End Sub
This works perfectly fine for me!
Mary's solution looks great, and I will give it a shot in the future when I need a modular input.
Thanks again for all the help!
I tested your solution, and it doesn’t produce the described results.
See test and correct solution at: https://dotnetfiddle.net/v5wGng
A couple of things from your original problem, you should prefer calculation to loops wherever possible, and you should use the required types wherever possible. If you have date in one format (string) and need it in another for your calculations, you should do the conversion and then call a function that does your calculations where all of the parameters are of the correct type.
Public Function GetSameWeekAndWeekDay(dt as date, months as integer) as Date
Dim newMonth =(new date(dt.year, dt.month, 1)).AddMonths(Months)
Dim week = getweek(dt)
Dim sameWeekDay = GetNthDayOfWeek(newMonth, week, dt.DayOfWeek)
Return SameWeekday
End Function
Public Function GetWeek(dt as date) as integer
Return(dt.day - 1) \ 7
End Function
Public Function GetNthDayOfWeek(dt as date, week as integer, weekDay as System.DayofWeek) as Date
Dim first = new Date(dt.year, dt.month, 1)
Dim baseDate = first.AddDays(-(first.DayOfWeek - system.dayofweek.Sunday))
Dim newDate = baseDate.AddDays((week * 7) + weekday)
If(newdate.DayOfWeek < first.DayOfWeek) then
newDate = newDate.AddDays(7)
End If
Return newdate
End Function
I'm attempting to display a button on a secondary form in vb based on what the date is (Trying to get a reset button to show only on the last day of the year).
I've tried a few different things with the code below...
I originally put it in the Form Load Event of Form 2, no msgbox displayed, button didn't display.
I cut the code out of my project and pasted it into the Form Load Event of a new project to test it on it's own... Msgbox displayed and button displayed!! :)
This got me thinking maybe I had to put the code into the Form Load Event of the Main Form. I pasted it there and made the modifications to point to form2 (Current version of the code)....
Once again , no msgbox, no button
What am I missing?
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim date1 As String = String.Format("{0:MM/dd/yyyy}", DateTime.Now)
Dim todaysdate As String = Format(Now, "Long Date")
Dim dayofweek = todaysdate.Substring(0, todaysdate.IndexOf(","))
Dim year As String = Now.Year
Dim datecheck As String = "12/29/"
Dim datecheck1 As String = "12/30/"
Dim datecheck2 As String = "12/31/"
' Add Current Year to Date to Check variables
datecheck = datecheck + year
datecheck1 = datecheck1 + year
datecheck2 = datecheck2 + year
Dim expenddt As Date = Date.ParseExact(date1, date1, System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt1 As Date = Date.ParseExact(datecheck, datecheck,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt2 As Date = Date.ParseExact(datecheck1, datecheck1,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt3 As Date = Date.ParseExact(datecheck2, datecheck2,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
' If DEC 29 or 30 Falls Fiday, Display Reset Button
If date1 = datecheck And dayofweek = "Friday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!")
Form2.Reset.Visible = True
End If
If date1 = datecheck1 And dayofweek = "Friday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!!")
Form2.Reset.Visible = True
End If
' If it's Dec 31 and it's Not Saturday or Sunday, Display Reset Button
If date1 = datecheck2 and dayofweek <> "Saturday" and dayofweek <> "Sunday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!!!")
Form2.Reset.Visible = True
End If
End Sub
First things first, have a read through the documentation for the DateTime structure. You can do everything that you're trying to do without using Strings. The DateTime structure has a DayOfWeek property, and Month and Day properties that will help you here.
Secondly, the way you are using the ParseExact method is wrong (not that you should end up using it). The second parameter to the ParseExact method is the format string that you expect the date to be in (something like "MM/dd/yyyy"). Passing in a formatted date will not work, and from my experiments, will simply return the current date without any parsing occurring.
So, with all that in mind (and assuming you want to show the button on the last weekday in the year as your code suggests, and not just the last day in the year as your question stated), try something like this:
Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Form2.Reset.Visible = ShouldShowResetButton(DateTime.Now)
End Sub
Private Function ShouldShowResetButton(currentDate As DateTime) As Boolean
Return GetLastWeekdayInYear(currentDate.Year) = currentDate.Date
End Function
Private Function GetLastWeekdayInYear(year As Integer) As Date
Dim lastDayInYear As Date
lastDayInYear = New Date(year, 12, 31)
Select Case lastDayInYear.DayOfWeek
Case DayOfWeek.Sunday
Return New Date(year, 12, 29)
Case DayOfWeek.Saturday
Return New Date(year, 12, 30)
Case Else
Return lastDayInYear
End Select
End Function
I have 1 String in VB.net
Dim str As String = "2014/08/15 19:45"
I have 2 time
Dim startDate As String = "6:30"
Dim endDate As String = "22:00"
How to compare "str" with "startDate" & "endDate" ?
First, you have strings not DateTimes or TimeSpan. But you need both if you want to compare them. So use Date.Parse, Date.ParseExact (or the ...TryParse versions to check invalid data):
Dim str As String = "2014/08/15 19:45"
Dim dt1 = Date.ParseExact(str, "yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture)
Dim startDate As String = "6:30"
Dim tsStart = TimeSpan.Parse(startDate)
Dim endDate As String = "22:00"
Dim tsEnd = TimeSpan.Parse(endDate)
Now you can compare them:
If dt1.TimeOfDay >= tsStart AndAlso dt1.TimeOfDay <= tsEnd Then
' Yes, 19:45 is between 6:30 and 22:00 '
End If
First, you should be using dates to store the values. Then it's a simple matter of checking the time components. Note that the implementation below is inclusive (i.e. if the time is exactly the start or end time, it will print the message.
Dim dateToCheck As Date = Date.Parse("2014/08/15 19:45")
' The date portion doesn't matter, so I'm just using 1/1/1970.
Dim startTimeDate As Date = New Date(1970, 1, 1, 6, 30, 0)
Dim endTimeDate As Date = New Date(1970, 1, 1, 22, 0, 0)
Dim afterOrEqualToStartTime As Boolean = (dateToCheck.Hour >= startTimeDate.Hour) And (dateToCheck.Minute >= startTimeDate.Minute) And (dateToCheck.Second >= startTimeDate.Second)
Dim beforeOrEqualToEndTime As Boolean = (dateToCheck.Hour <= endTimeDate.Hour) And (dateToCheck.Minute <= endTimeDate.Minute) And (dateToCheck.Second <= endTimeDate.Second)
If (afterOrEqualToStartTime And beforeOrEqualToEndTime) Then
MsgBox("Date is between the start and end times")
End If
Dim str As String = "2014/08/15 19:45"
Dim time As DateTime = DateTime.Parse(str)
'here get the hour and minutes, and now you can compare with the others
Dim tmpTime As DateTime = time.ToString("t")
Comparing time is difficult using Date variables.
Using a data difference, with a tolerance, is one way to deal with binary time.
I use strings:
Dim dt As Date = "2014/08/15 22:45"
Dim s As String = dt.ToString("H:MM")
If s > "06:30" And s <= "22:00" Then
MsgBox("yes")
Else
MsgBox("no")
End If
note the leading 0 in 06:30 in the sample.
I am trying to subtract two times.
Sub notifier(checkouttime As Label)
Dim checktime As New DateTime(checkouttime.Tag)
Dim currenttime As New DateTime(DateAndTime.TimeOfDay.ToString("hh:mm:ss"))
Dim balance As TimeSpan = checktime - currenttime
End Sub
on my checkouttime.tag has a time value of under this format "hh:mm:ss"
and I have to get the current time for today with the same format and I achieve it but when I need to subtract them I am getting an error.
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "08:00:58" to type 'Long' is not valid.
Thanks in advance
This will try to parse your DateTime string. You may need to save a date with time that you save to your Tag property.
Private Function Notifier(checkouttime As Label) As String
Dim checktime As DateTime
If DateTime.TryParse(checkouttime.Tag.ToString, checktime) Then
Dim currenttime As Date = Date.Now
Return (currenttime - checktime).ToString()
End If
Return "Bad Time String"
End Sub
Try this kind of format...
Dim date1 As Date = #2/14/2014 9:35:04 AM#
Dim date2 As Date = #2/28/2014 12:30:54 PM#
Dim duration As TimeSpan = date1 - date2
MsgBox(duration.ToString)
Nevermind, I have found another similar solution for my problem and here is how I solve it.
Sub notifier(checkouttime As Label)
Dim checktime As String = checkouttime.Tag
Dim splitcheck = Split(checktime, ":")
Dim currenttime As String = CStr(DateAndTime.TimeOfDay.ToString("hh:mm:ss"))
Dim splitcurrent = Split(currenttime, ":")
Dim checkMinutes, currentMinutes As Integer
checkMinutes = CDbl(splitcheck(0)) * 60 + CDbl(splitcheck(1)) + CDbl(splitcheck(2)) / 60
currentMinutes = CDbl(splitcurrent(0)) * 60 + CDbl(splitcurrent(1)) + CDbl(splitcurrent(2)) / 60
'Dim balance As String = checkkresult - currentresult
MsgBox(checkMinutes & " " & currentMinutes & ". While current time is: " & currenttime)
End Sub
I converted the time to minutes to achieve my goals.
Thanks for your answer guys.