IDataReader - Get value of SQL time(7) field to use in calculations - asp.net

Using IDataReader, I need to get time values so that I can get the timespan. In my SQL database, these values are time(7). I am getting an error - InvalidCast Exception was unhandled by user code. Here is my code (and I know I have to rewrite the Select statement):
commandvct.CommandText = "Select begindateoff, enddateoff, begintimeoff, endtimeoff, allday_yesno from tblworkhours where Employee = " & rve & " and workcode = 2"
commandvct.CommandType = CommandType.Text
commandvct.Connection = sqlConnection
sqlConnection.Open()
Using reader As IDataReader = commandvct.ExecuteReader
While reader.Read()
Dim begdate As Date = reader.GetDateTime(0)
Dim enddate As Date = reader.GetDateTime(1)
If begdate = enddate Then
Dim allday As Boolean = reader.GetBoolean(4)
'If all day, add 8 hours
If (allday = True) Then
workinghoursv = workinghoursv + 8 'Change me to your needs.
TextBoxva2.Text = workinghoursv
'If not all day, add difference between times
Else
'tried defining it as datetime and as string - neither work
Dim begtime As String = reader.GetDateTime(2)
Dim endtime As DateTime = reader.GetDateTime(3)
Dim diffv As TimeSpan = (endtime).Subtract(begtime)
Dim diff2v As Decimal = (Convert.ToDecimal(diffv.TotalMinutes)) / 60
workinghoursv = workinghoursv + diff2v
TextBoxva2.Text = workinghoursv
End If

Related

How can I calculate number of days between 2 dates?

I have a reservation page and a reservation table which contains reservationstart column, reservationend column and numofdays column.
I have determined the number of days between the two dates which a client will select but nothing was stored in the table when I update.
The data type of numofdays was datatime but I have changed this to int.
I used this first, to declare the start and end date:
DayPilotScheduler1.Scale = TimeScale.Manual
Dim start As New Date(Date.Today.Year, 1, 1, 12, 0, 0)
Dim [end] As Date = start.AddYears(1)
This is the code for the update:
Protected Sub DayPilotScheduler1_EventMove(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMoveEventArgs)
Dim id_Renamed As String = e.Value
Dim start As Date = e.NewStart
Dim [end] As Date = e.NewEnd
Dim resource As String = e.NewResource
Dim message As String = Nothing
If Not dbIsFree(id_Renamed, start, [end], resource) Then
message = "The reservation cannot overlap with an existing reservation."
ElseIf e.OldEnd <= Date.Today Then
message = "This reservation cannot be changed anymore."
ElseIf e.OldStart < Date.Today Then
If e.OldResource <> e.NewResource Then
message = "The room cannot be changed anymore."
Else
message = "The reservation start cannot be changed anymore."
End If
ElseIf e.NewStart < Date.Today Then
message = "The reservation cannot be moved to the past."
Else
dbUpdateEvent(id_Renamed, start, [end], resource)
'message = "Reservation moved.";
End If
LoadResourcesAndEvents()
DayPilotScheduler1.UpdateWithMessage(message)
End Sub
Private Sub dbUpdateEvent(ByVal id As String, ByVal start As Date, ByVal [end] As Date, ByVal resource As String)
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString)
con.Open()
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
Dim cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource,numofday=#numofday WHERE ReservationId = #id", con)
cmd.Parameters.AddWithValue("id", id)
cmd.Parameters.AddWithValue("start", start)
cmd.Parameters.AddWithValue("end", [end])
cmd.Parameters.AddWithValue("resource", resource)
cmd.Parameters.Add("numofday", SqlDbType.Int).Value = numOfDay
cmd.ExecuteNonQuery()
End Using
End Sub
Screenshot of database table structure:
Math.floor(Math.abs(new Date(timestringone) - new Date(timestringtwo))/(1000*60*60*24))
Simply subtracting the dates returns the time in Milliseconds inbetween them. If the first time was before the second time the value is negative, so i used Math.abs to make it absolute. Then we divide trough 1000Milliseconds=1second, 60seconds=1minute, 60minutes=1hour, 24hours=1 day, and floor it to whole days. Requires two valid timestrings (timestringone and timestringtwo) to be given.
This is a javascript solution as youve included the js tag...
I am not sure about the VB.Net but you can easily accomplished it in C# using an object of Type "TimeSpan". For example: let's assume that we want to know the number of days between the start and end. values for the DateTime Type and show it in a Console window, then I may write something like:
DateTime start=DateTime.MinValue;
DateTime end=DateTime.MaxValue;
TimeSpan span=end-start;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, start.ToString(), end.ToString() );
OP is having problems using the .Days property on the TimeSpan structure. I think this may help:
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
The output is:
365
Moving onto the use of your parameters, I think you would benefit from using .Add and specifying the data type:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = numOfDay
Note that you may have to change the SqlDbType. I've taken an assumption.
I would also implement Using for both the SqlConnection and SqlCommand. This for me is just good practice and the code does read better. I would also use the .Add overload for all parameters.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString),
cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource, numofday = #numofday WHERE ReservationId = #id", con)
con.Open()
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = CInt(([end] - start).TotalDays())
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
If rowsAffected = 0 Then
'nothing updated
Else
'something updated
End If
End Using

Trouble getting date value

I am modifying a webpage. Webpage is using visual basic and my database is a SQL database.
The webpage gives me the total Sick, Comp, and Vacation time off. Right now, I get the logon name of whoever's logged onto the computer, and I look up the EmployeeID in a tblEmployees so I can search tblTimeAvailable by the EmployeeID, and then add up the different times.
I want to also get the StartDate from tblEmployees so I can also search by anniversary date (after I calculate it from the Start Date). I'm getting an error "Value of type 'Integer' cannot be converted to 'Date' on the rvsd=command2.ExecuteNonQuery line. Here's my code:
Dim rve As Object
Dim rvsd As Date
Dim dt As Date = Today
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim sqlstdt As String = "SELECT StartDate FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
Dim command2 As New SqlCommand(sqlstdt, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
command2.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
rve = command.ExecuteScalar
rvsd = command2.ExecuteNonQuery
End Using
Dim theDateThisYear As Date
theDateThisYear = DateSerial(Year(Now), Month(rvsd), Day(rvsd))
If theDateThisYear < Now() Then
theDateThisYear = DateAdd("yyyy", 1, theDateThisYear)
End If
Dim NextAnniversary As Date = theDateThisYear
MsgBox(NextAnniversary)
'Get Sick Time - DOES NOT INCLUDE CHECKING TO MAKE SURE LESS THAN ANNIV DATE YET
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #emp"
Dim command As New SqlCommand(sqls1, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#emp", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
rvsa = command.ExecuteScalar
End Using
Thanks in advance for any help you can give me!
Assuming that the column [StartDate] in the database has a type of DateTime then all you need to do is
rvsd = CDate(command2.ExecuteScalar)
Although you could have retrieved both values with one query:
SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
and so
Dim rve As String
Dim rvsd As Date
Dim connStr As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Dim sql = "SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(Sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
rve = rdr.GetString(0)
rvsd = rdr.GetDateTime(1)
End If
End Using
End Using

Year, Month, and Day parameters describe an un-representable DateTime exception in method execution

I am having the above exception come up when executing my method (code below):
Sub loadDates(ByVal newDate As Date)
Dim dayCount As Integer = 0
conn = New SqlConnection(connectionString)
ds = New DataSet("Holiday")
sql = New SqlCommand("SELECT * FROM Holiday", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter("SELECT date FROM Holiday", conn)
conn.Open()
da.FillSchema(ds, SchemaType.Source, "Holiday")
da.Fill(ds, "Holiday")
Dim tblHoliday As DataTable
tblHoliday = ds.Tables("Holiday")
For Each row As DataRow In tblHoliday.Rows
If Not row Is Nothing Then
For items As Integer = 0 To tblHoliday.Rows.Count Step 1
Dim dateValue As Date = row.Item(0)
If newDate = dateValue Then
dayCount += 1
End If
Exit For
Next
End If
Next
conn.Close()
If newDate.DayOfWeek = DayOfWeek.Saturday Or newDate.DayOfWeek = DayOfWeek.Sunday Then
dayCount = 2
End If
For days As Integer = dayCount To 0 Step -1
Dim dropDates As Date = New Date(newDate.Year, newDate.Month, newDate.Day - days)
ddDate.Items.Add(dropDates.ToShortDateString())
Next
End Sub
I've narrowed down the problem to being within the For Each loop in the method, when I enter in a date and it skips over the loop it works without a problem. When it has to go through the loop it crashes on the line:
Dim dropDates As Date = New Date(newDate.Year, newDate.Month, newDate.Day - days)
Any ideas?
Subtract the days from the date instead of from the day component, that way the day compontent doesn't get out of range:
Dim dropDates As Date = New Date(newDate.Year, newDate.Month, newDate.Day).AddDays(-days)
If newDate doesn't have any time component component that you are getting rid of by using that Date constructor, you can just use newDate directly:
Dim dropDates As Date = newDate.AddDays(-days)

Calculating % of days VB.NET

How is it possible to calculate the percentage of days completed by using VB.NET?
The datareader takes project_start and project_finished, stored as Date() in SQL-Server-2012.
This is what I tried:
Dim StartDate As New Date(datareader("project_start"))
Dim FinishDate As New Date(datareader("project_finish"))
Dim Percentage As Date = Date.FromOADate(StartDate.DayOfYear) / Date.FromOADate(FinishDate.DayOfYear) / 100
But I get this error:
Operator '/' is not defined for types 'Date' and 'Date'.
You need to substract Dates and use TotalDays property. The example code below:
Dim start As DateTime = DateTime.Now.AddDays(-50)
Dim endDate As DateTime = DateTime.Now.AddDays(50)
Dim today As DateTime = DateTime.Now
Dim sumDays = (endDate - start).TotalDays
Dim daysToNow = (today - start).TotalDays
Dim percentage = daysToNow / sumDays * 100
Console.WriteLine(percentage)
Console.ReadLine()

How can i minus two Dates asp.net

How can i minus two Dates (LblExpirydate.Text - Label3.Text )
LblExpirydate.Text = String.Format("{0:dd/MM/yyyy}", dataReader(0))
Label3.Text = System.DateTime.Now.ToString(("dd/MM/yyyy"))
LblExpirydate.Text = 01/05/2013
Label3.Text = 01/04/2011
You can subtract one date from another to get a TimeSpan. You should not try to do date calculations on strings: your program is likely to fall foul of an assumed date format somewhere.
Dim dateFormat As String = "dd/MM/yyyy"
Dim rightNow As DateTime = DateTime.Now
Dim expiryDate As DateTime = rdr.GetDateTime(0)
Dim daysToExpiry As Integer = (expiryDate - rightNow).Days
LblExpirydate.Text = expiryDate.ToString(dateFormat)
Label3.Text = expiryDate.ToString(dateFormat)
LabelExpires.Text = daysToExpiry.ToString & " days"

Resources