How to compare only month and year? [VB] - vb.net

Its quite simple, i just want to compare two dates using month and year, if the input date (mont and year only) are above or below that current date (month and year).
The problem is , when i compare two strings
Dim dDate as DateTime
If Not (DateTime.TryParse(txtBox.Text, dDate)) Then
MessageBox.Show("check date.")
Else
txtBox.Text = dDate.ToString("MM/yyyy")
end If
IF dDate.ToString("MM/yyyy") < DateTime.Now.ToString("MM/yyyy")
MessageBox.Show("Below") ' Problem: 03/2024 saying is below than 08/2019
Else
MessageBox.Show("Above")
End If
Any help?
UPDATE
I CHANGED THE CASE TO
If (dDate.Month AndAlso dDate.Year) < (DateTime.Now.Month AndAlso DateTime.Now.Year) Then
'input: 07/2019
'date expired
Else
'the problem is here
'saying 07/2019 is not < than 08/2019
End If

I'd avoid using strings.
Dim dDate As DateTime
If Not (DateTime.TryParse(txtBox.Text, dDate)) Then
'bad date
MessageBox.Show("check date.")
Else
Select Case dDate.Year
Case Is < DateTime.Now.Year
MessageBox.Show("Below")
Case Is > DateTime.Now.Year
MessageBox.Show("Above")
Case Else 'years are equal,check month
Select Case dDate.Month
Case Is < DateTime.Now.Month
MessageBox.Show("Below")
Case Is > DateTime.Now.Month
MessageBox.Show("Above")
Case Else 'equal months
MessageBox.Show("SAME") '????
End Select
End Select
End If

Using date values is probably best, but if string comparisons must be made.
Dim dDate as DateTime
If Not (DateTime.TryParse(txtBox.Text, dDate)) Then
MessageBox.Show("check date.")
Else
txtBox.Text = dDate.ToString("yyyyMM")
End If
If dDate.ToString("yyyyMM") < DateTime.Now.ToString("yyyyMM") Then
MessageBox.Show("Below")
ElseIf dDate.ToString("yyyyMM") > DateTime.Now.ToString("yyyyMM") Then
MessageBox.Show("Above")
Else
MessageBox.Show("Same")
End If

Thank you everyone, but the final solutions is made with
If (dDate.Year < DateTime.Now.Year Or (dDate.Year = DateTime.Now.Year And dDate.Month < DateTime.Now.Month)) Then
'something
Else
'something
End If

Convert the year and month to Integer values, which are easy to compare less-than or greater-than. For example, if you had two DateTimePicker controls on a form, named dtpDate1 and dptDate2, and a button btnTest:
Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
Dim date1 As Integer = (dtpDate1.Value.Year * 100) + dtpDate1.Value.Month
Dim date2 As Integer = (dtpDate2.Value.Year * 100) + dtpDate2.Value.Month
MsgBox("Date1 = " & date1.ToString & vbCrLf & "Date2 = " & date2.ToString)
If date1 = date2 Then MsgBox("Equal!")
If date1 < date2 Then MsgBox("date1 is less than date2")
If date1 > date2 Then MsgBox("date1 is greater than date2")
End Sub
The dates are converted to integers in a YYYYMM format. This is a data warehouse technique to convert dates to integers for better query performance when date is used often in a WHERE clause.

Related

Find end date given startdate in MS ACCESS

I'm attempting to write a formula that rounds an end date it to the nearest workday given the start date. I will want the flexibility to add the number of days to start date. For example, if I have the dates November 27, 2021 (which is a Saturday) and November 28, 2021 (which is a Sunday) I want the formula to return November 29, 2021 (Monday). However, if the date November 26, 2021 return same date since it’s a working day. The date will also move to the next working day if the Date is a holiday. Thanks
Public Function AddDueDate(StartDate As Date, TotalPeriold As Integer) As Date
Dim rst As Recordset
Dim db As Database
Dim Duedate As Date
Dim icount As Integer
On Error GoTo errhandlers:
Set db = CurrentDb
Set rst = db.OpenRecordset("tblHolidays", dbOpenSnapshot)
icount = 0
Duedate = StartDate
Do While icount < TotalPeriod
Duedate = Duedate + 1
If Weekday(Duedate, vbMonday) < 6 Then
rst.FindFirst "[Holidaydate]=#" & Duedate & "#"
If rst.NoMatch Then
icount = icount + 1
End If
End If
Loop
AddDueDate = Duedate
exit_errhandlers:
rst.Close
Set rst = Nothing
Set db = Nothing
Exit Function
errhandlers:
MsgBox Err.Description, vbExclamation
Resume Next
End Function
You can obtain that with a combo of my functions found in my project at VBA.Date:
WorkdayDate = DateAddWorkdays(Abs(Not IsDateWorkday(YourDate)), YourDate)
which will add zero days to a date of a workday but, for a non-workday, return the following date of workday.
Full code is too much to post here, but this is the core function:
' Adds Number of full workdays to Date1 and returns the found date.
' Number can be positive, zero, or negative.
' Optionally, if WorkOnHolidays is True, holidays are counted as workdays.
'
' For excessive parameters that would return dates outside the range
' of Date, either 100-01-01 or 9999-12-31 is returned.
'
' Will add 500 workdays in about 0.01 second.
'
' Requires table Holiday with list of holidays.
'
' 2021-12-09. Gustav Brock. Cactus Data ApS, CPH.
'
Public Function DateAddWorkdays( _
ByVal Number As Long, _
ByVal Date1 As Date, _
Optional ByVal WorkOnHolidays As Boolean) _
As Date
Const Interval As String = "d"
Dim Holidays() As Date
Dim Days As Long
Dim DayDiff As Long
Dim MaxDayDiff As Long
Dim Sign As Long
Dim Date2 As Date
Dim NextDate As Date
Dim DateLimit As Date
Dim HolidayId As Long
Sign = Sgn(Number)
NextDate = Date1
If Sign <> 0 Then
If WorkOnHolidays = True Then
' Holidays are workdays.
Else
' Retrieve array with holidays between Date1 and Date1 + MaxDayDiff.
' Calculate the maximum calendar days per workweek.
If (WorkDaysPerWeek - HolidaysPerWeek) > 1 Then
MaxDayDiff = Number * DaysPerWeek / (WorkDaysPerWeek - HolidaysPerWeek)
Else
MaxDayDiff = Number * DaysPerWeek
End If
' Add one week to cover cases where a week contains multiple holidays.
MaxDayDiff = MaxDayDiff + Sgn(MaxDayDiff) * DaysPerWeek
If Sign > 0 Then
If DateDiff(Interval, Date1, MaxDateValue) < MaxDayDiff Then
MaxDayDiff = DateDiff(Interval, Date1, MaxDateValue)
End If
Else
If DateDiff(Interval, Date1, MinDateValue) > MaxDayDiff Then
MaxDayDiff = DateDiff(Interval, Date1, MinDateValue)
End If
End If
Date2 = DateAdd(Interval, MaxDayDiff, Date1)
' Retrive array with holidays.
Holidays = DatesHoliday(Date1, Date2)
End If
Do Until Days = Number
If Sign = 1 Then
DateLimit = MaxDateValue
Else
DateLimit = MinDateValue
End If
If DateDiff(Interval, DateAdd(Interval, DayDiff, Date1), DateLimit) = 0 Then
' Limit of date range has been reached.
Exit Do
End If
DayDiff = DayDiff + Sign
NextDate = DateAdd(Interval, DayDiff, Date1)
Select Case Weekday(NextDate)
Case vbSaturday, vbSunday
' Skip weekend.
Case Else
' Check for holidays to skip.
' Ignore error when using LBound and UBound on an unassigned array.
On Error Resume Next
For HolidayId = LBound(Holidays) To UBound(Holidays)
If Err.Number > 0 Then
' No holidays between Date1 and Date2.
ElseIf DateDiff(Interval, NextDate, Holidays(HolidayId)) = 0 Then
' This NextDate hits a holiday.
' Subtract one day before adding one after the loop.
Days = Days - Sign
Exit For
End If
Next
On Error GoTo 0
Days = Days + Sign
End Select
Loop
End If
DateAddWorkdays = NextDate
End Function

how to compare 2 datetimepicker vb.net

I'd like to compare 2 DateTimePicker's value
Dim dd1 As Date, dd2 As Date
Dim diff As Integer
dd1 = DateTimePicker1.Value
dd2 = DateTimePicker2.Value
diff = DateDiff("d", dd1, dd2)
If diff > 0 Then
MsgBox("datetimpicker1datetimepicker2")
End If
but it doesn't work could you help me please
Another way to compare would be to use the DateTime.Compare function. For a simple "Are they the same?" you could try:
If Not DateTime.Compare(dd1,dd2) = 0 then
'they are diffent
End If
Or if you want to be more specific then you might go with something like this:
If Not DateTime.Compare(dd1,dd2) = 0 then
'they are same
ElseIf DateTime.Compare(dd1,dd2) > 0 then
'dd1 is later than dd2
Else
'dd1 is prior to dd2
End If
You can see more about DateTime.Comare here on MSDN
If You are using DateDiff() then there are three case can be possible:-
1) DatePicker1 date is bigger than DatePicker2
2) DatePicker1 date is lower than DatePicker2
3) DatePicker1 date is equal to DatePicker2
To handle this, You have to use this
diff = DateDiff("d", dd1, dd2)
If diff > 0 Then
MsgBox("datetimpicker1 is greater than datetimepicker2")
Else If diff < 0 Then
MsgBox("datetimpicker1 is lesser than datetimepicker2")
Else
MsgBox("datetimpicker1 is equal to datetimepicker2")
End If

Obtain period by subtract start datetime and end datetime with workday

I am trying to implement a method in VB.NET that could subtract a start datetime and datetime, and result this specific string period "D.HH:mm:ss", observing that the day doesn't have 24 hours, but only 8 hours.
My function to do the subtract return only the diff in hours and as decimal:
Public Function WH(ByVal date1 As Date, ByVal date2 As Date,
Optional ByVal considerwk As Boolean = True) As Decimal
Dim ini_tim As DateTime = DateTime.Parse("08:00")
Dim end_tim As DateTime = DateTime.Parse("18:00")
'//RESULT
Dim _res As Integer
'//WHILE INITIAL LESS THAN END...
Do While date1 <= date2
'//INSIDE INTERVAL?
If Hour(date1) >= Hour(ini_tim) And Hour(date1) <= Hour(end_tim) Then
'//CONSIDER WORKDAY?
If considerwk = True Then
'//IF NOT SATURDAY OR SUNDAY
If Weekday(date1) <> vbSaturday And Weekday(date1) <> vbSunday Then
'//ADD +1 IN RESULT
_res += 1
End If
Else
'//ADD +1 IN RESULT
_res += 1
End If
End If
'//ADD A MINUTE IN THE DATE
date1 = DateAdd("n", 1, date1)
Loop
'//RETURN THE DIFF IN DEC
Return CDec(_res / 60)
End Function
Hope that you can help me!
Thanks!
Something to consider...
With your current code:
Hour(date1) <= Hour(end_tim)
A time of 18:01 would be considered "inside the interval" when it's actually after the end time!
Try something more like below. It'll be accurate down to the second and can handle it if your start/stop times are not exactly at the top of the hour (like 08:30 to 18:30):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt1 As DateTime = DateTime.Now
Dim dt2 As DateTime = dt1.AddDays(5).AddHours(4).AddMinutes(39).AddSeconds(17)
Dim ts As TimeSpan = WH(dt1, dt2, True)
Dim strFormattedTotal As String = String.Format("{0}.{1}:{2}:{3}", ts.Days, ts.Hours.ToString("00"), ts.Minutes.ToString("00"), ts.Seconds.ToString("00"))
Label1.Text = "Total: " & strFormattedTotal
Label2.Text = "Total Hours: " & ts.TotalHours
End Sub
Public Function WH(ByVal date1 As Date, ByVal date2 As Date, Optional ByVal considerwk As Boolean = True) As TimeSpan
Static ini_tim As DateTime = DateTime.Parse("08:00")
Static end_tim As DateTime = DateTime.Parse("18:00")
Dim TS As New TimeSpan
Do While date1 < date2
If date1.TimeOfDay >= ini_tim.TimeOfDay AndAlso date1.TimeOfDay <= end_tim.TimeOfDay Then
If considerwk Then
If date1.DayOfWeek <> DayOfWeek.Saturday AndAlso date1.DayOfWeek <> DayOfWeek.Sunday Then
TS = TS.Add(TimeSpan.FromSeconds(1))
End If
Else
TS = TS.Add(TimeSpan.FromSeconds(1))
End If
End If
date1 = date1.AddSeconds(1)
Loop
Return TS
End Function

Returning the exact date difference without using DateDiff

I need to return the exact difference between two dates in the form of a string.
If the dates are 01-FEB-2012 and 01-FEB-2014, the function should return "2 years".
If the dates are 01-FEB-2012 and 01-MAR-2014, the function should return "25 months".
If the difference is not in exact years or months, it should return the difference in days.
I do not want to use DateDiff from the Visual Basic namespace so the code is portable to C#.
'Assuming d1 < d2
Public Function GetDateDiff(d1 as DateTime, d2 As DateTime) As String
If d1.Day = d2.Day Then
Dim yearDiff As Integer = d2.Year - d1.Year
If d1.Month = d2.Month Then
'Only year differs
Return yearDiff & " years"
Else
'Month and year differs
Dim monthDiff As Integer = d2.Month - d1.Month
Return (yearDiff * 12 + monthDiff) & " months"
End If
Else
Return (d2-d1).TotalDays & " days"
End If
End Function

How to compare just the date part and not the time of two Dates?

I want to compare just the date part (and Not the time) of two VB.NET Date objects.
Is there a way to do that?
Just take the date part of each via the Date property and compare the two:
date1.Date.CompareTo(date2.Date)
Or:
If date1.Date < date2.Date Then
You could also use TimeSpan
Dim ts As TimeSpan
ts = dt1 - dt2
ts.Days will now have the difference of the two dates as whole days.
Compare the DateTime.Date properties.
Change the txt1 date to format dd/mm/yyyy using myDateTime.ToShortDateString() so that both the dates will be in same format.
then :
if (DateTime.Compare(date1, date2) > 0)
// which means ("date1 > date2")
if (DateTime.Compare(date1, date2) == 0)
//which means ("date1 == date2");
if (DateTime.Compare(date1, date2) < 0)
//which means ("date1 < date2");
Dim backDateCount As Integer = DateDiff(DateInterval.Day, CDate(dtpCheckIn.SelectedDate.Value).Date, Date.Now.Date)
Date.Now.Date: #12/4/2018 12:00:00 AM#
Date.Now: #12/4/2018 03:23:34 PM#
Dim date1, date2 As Date
date1 = Date.Parse(dtpStart.Text)
date2 = Date.Parse(dtpEnd.Text)
If (DateTime.Compare(date1, date2) > 0) Then ' which means ("date1 > date2")
MessageBox.Show("يجب تحديد الفترة للتاريخ بشكل صحيح ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading)
Exit Sub
End If