Compare time in ASP/VB - asp.net

I have 2 columns, one for start-time and the other for the end-time. They both are of the type nvarchar so that i can compare them.
I have a text box that will receive time from the user and will post-back automatically to check if the the time is valid or not.
Dim compared_time_1 As DateTime
Dim compared_time_2 As DateTime
Dim select_time As SqlCommand
select_time = New SqlCommand("select Start_Time , End_Time from Clinic_Schedule where Schedule_no = #sch_no", appt_DB_1)
select_time.Parameters.AddWithValue("#sch_no", Sch_no)
Dim time_rdr As SqlDataReader
time_rdr = select_time.ExecuteReader()
While time_rdr.Read
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
If appt_time_txt0.Text >= start_time_1 And appt_time_txt0.Text <= end_time_1 Then
date_valid_lbl0.Visible = True
date_valid_lbl0.Text = "*Valid Time"
Else
time_valid_lbl0.Visible = True
time_valid_lbl0.Text = "*Not Valid Time"
End If
End While
time_rdr.Close()
I don't know if i have a problem with my logic XD.
the data filled in thoses columns are in this format : 00:00AM or 00:00PM.
I will appreciate your help .. thanks

Seems like you are comparing a string against a date datatype.
Ensure that you are converting both into date datatype as follows.
Note the space between the seconds and 'AM'.
time1=CDate("3:19:40 AM")
time2=CDate("3:10:40 AM")
Then perform comparisms as follows:
if time1>time2 then
'logic
end if

It looks like you're doing the parse before loading the data from your reader.
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
should be
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
But I would even do it differently than that. If you're trying to tell if the times are valid, you can use the datetime TryParse method. Perhaps a bit of refactoring might also help you. Finally, just be aware that comparing times might be problematic if there is ever a chance that schedule item might begin before midnight and end after midnight the next day.
Sub ReadingData()
'initializing reader stuff here...
Dim dtStart As DateTime, dtEnd As DateTime
If DateTime.TryParse(time_rdr(0).ToString, dtStart) = False Then
HandleInvalidTime()
End If
If DateTime.TryParse(time_rdr(1).ToString, dtEnd) = False Then
HandleInvalidTime()
End If
'Closing out reader stuff here...
HandleValidTime(dtStart, dtEnd)
End Sub
Sub HandleValidTime(TheStartTime As DateTime, TheEndTime As DateTime)
'Do Stuff
End Sub
Sub HandleInvalidTime()
'Do Stuff
End Sub

Related

Add Days to Date with 'YYYYMMDD' format

In VB6, I am trying to add days to a date which is in the format 'YYYYMMDD'. I can add days like this:
Pull_Date = Need_Date + Val(txtLeadTime.Text)
which works, until the resulting days is greater than the number of days in the month. I tried using DateAdd, but it doesn't accept the YYYYMMDD format - neither does CDate.
You need to convert your date string to a date so you can use the DateAdd function:
Dim Need_Date As String
Dim Pull_Date As Date
Dim tmpDate As Date
Need_Date = "20141113"
tmpDate = CDate(Mid$(Need_Date, 5, 2) & "/" & Right$(Need_Date, 2) & "/" & Left$(Need_Date, 4))
Pull_Date = DateAdd("d", Val(txtLeadTime.Text), tmpDate)
MsgBox Format$(Pull_Date, "yyyymmdd") '// if LeadTime is 25 days, displays 20141208
Please note, parsing your Need_Date by character position can blow up if it's not formatted exactly as expected.
After digging deeper into this old code, I found that a conversion function was already created:
Public Function Date_Format_YYYYMMDD(ByVal sDate As String) As String
If IsDate(sDate) Then
sDate = Format(sDate, "YYYYMMDD")
End If
Date_Format_YYYYMMDD = sDate
End Function
With this function, it's really easy:
Pull_Date = Date_Format_YYYYMMDD(Need_Date) + Val(txtLeadTime.Text)
The only thing I don't understand is why
Pull_Date = Format(Need_Date, "YYYYMMDD") + Val(txtLeadTime.Text)
doesn't work. Seems like it's doing the same thing as the function.

Join Date and Time to DateTime in VB.NET

I am retrieving data from DB where there is a separate date and time fields. I want to join them into a DateTime field in my VB.NET project.
How would you suggest accomplishing this?
I tried this but it's not working for me.
"String was not recognized as a valid DateTime."
Dim InDate As New DateTime(incident.IncidentDate.Value.Year, incident.IncidentDate.Value.Month, incident.IncidentDate.Value.Day, 0, 0, 0)
Dim InTime As New DateTime(1900, 1, 1, incident.IncidentTime.Value.Hour, incident.IncidentTime.Value.Minute, incident.IncidentTime.Value.Second)
Dim combinedDateTime As DateTime = DateTime.Parse((InDate.ToString("dd/MM/yyyy") + " " + InTime.ToString("hh:mm tt")))
rdtpIncidentDateTime.SelectedDate = combinedDateTime
You can just create a new DateTime value from the components in InDate and InTime:
Dim combinedDateTime As DateTime = New DateTime( _
InDate.Year, InDate.Month, InDate.Day, _
InTime.Hour, InTime.Minute, InTime.Second _
)
DateTime exposes a method called DateTime.TimeOfDay
You can simply use DateTime.Add to append the time to the date.
Dim dateAndTime As DateTime = myDate.Add(myTime.TimeOfDay)
Dim CombinedDate As Date = Date1.Date + Time1.TimeOfDay
This will work when you want to combine the DATE from one variable and the TIME from a different variable.
Date is an alias to DateTime. In VB.NET, they are the same thing. You can see all the aliases in this chart on MSDN. Link
You can do it in one line...declare your indate and use the incident values for the time instead of zeros.

Dynamic gridview column value dependent on another column value

I have a gridview that has three bound fields. "Date", which is the day a support ticket was added; "Date Fixed", which is the day a support ticket was resolved; and "Days Waited", which should be the number of days a ticket has gone unresolved.
Each row has a different date and could or could not have a dateFixed. I can use the RowDataBound event to calculate daysWaited from date and dateFixed, but I do not know how to then set daysWaited to the calculated value for each row.
I am using VB.NET and the .NET 4.0 framework.
Not sure how you are loading data, hopefully setting the datasource of the gridview. After you set the datasource, you can call this method. It will go through and compare dates on each row, it also checks if anything is there. This worked good during my testing. Hopefully you find this good for your use.
Private Sub CalcDays()
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim stDate As Date
Dim endDate As Date
Dim daysPassed As Integer = -1
If Not (GridView1.Rows(i).Cells(1).Text = " ") Then
stDate = DateTime.Parse(GridView1.Rows(i).Cells(0).Text)
endDate = DateTime.Parse(GridView1.Rows(i).Cells(1).Text)
While (stDate <= endDate)
stDate = stDate.AddDays(1)
daysPassed += 1
End While
GridView1.Rows(i).Cells(2).Text = daysPassed.ToString
Else
GridView1.Rows(i).Cells(2).Text = "NA"
End If
Next
End Sub
Here's a screenshot of my test...

VB.NET Date Comparison Not Returning Correct Results?

I am pulling a date value from my database:
Dim qfresho = From p In dbConfig.Configs _
Where p.Description = "FROD" _
Select p.dateValue
Dim qfreshc = From p In dbConfig.Configs _
Where p.Description = "FRCD" _
Select p.dateValue
Then comparing these date values to the current date:
If qfresho.First.Value >= Date.Now And qfreshc.First.Value <= Date.Now Then
lblFreshman.Text = "Freshmen are currently eligible to register for a room."
Else
Dim frdays As TimeSpan
frdays = (qfresho.First.Value).Subtract(Now)
lblFreshman.Text = "Registration will open for freshmen in " & frdays.Days & " days."
End If
But for some reason its always returning the Else condition - even though the values in the database should make the query true. Any ideas? I'm guessing for some reason its not pulling the results as a date?
Date.Now returns a DateTime, so does your database have dates and times or just dates? If you just want the date, you can use Date.Today.
Do the dates have time components that could be throwing off the compares?
Why not just add two debugs before the comparison???
Debug.WriteLine(qfresho.First.Value.ToString("MM/dd/yyyy hh:mm:ss.ffff"))
Debug.WriteLine(qfreshc.First.Value.ToString("MM/dd/yyyy hh:mm:ss.ffff"))
That should help.

How to subtract a month from Date object?

How do I subtract a month from a date object in VB.NET?
I have tried:
Today.AddMonths(-1)
However, given that Today is 01-Jan-2010, the result I get is 01-Dec-2010. The answer I want is 01-Dec-2009.
Is there a convenient way of doing this within the .NET framework?
You actually have to transport Today into a variable and let that assignment work there. The following code will produce the result you expect (I just verified it because your post made me think twice).
Dim dt As DateTime = Date.Today
dt = dt.AddMonths(-2)
Dim x As String = dt.ToString()
This works fine, you need to remember that the DateTime is imutable.
Dim d As DateTime
d = New DateTime(2010, 1, 1)
d = d.AddMonths(-1)
Have a look at DateTime Structure
A calculation on an instance of
DateTime, such as Add or Subtract,
does not modify the value of the
instance. Instead, the calculation
returns a new instance of DateTime
whose value is the result of the
calculation.
Dim d As DateTime = #1/1/2010#
d = d.AddMonths(-1)
I have used the following and it works.
Dim dtToday As DateTime = Date.Today
dtToday = dtToday.AddMonths(-2)

Resources