S3.wp.wsu.edu



Using Calendars and Performing Time based Calculations project demonstrates how to work with dates and times that are entered into calendars and textboxes. A lot of progress has occurred in this area that simplifies the programming. Dates can be formatted in different ways, and date calculations are pretty easy. Easier than using DATEFIFF(in Excel) or SQL.Shown here is how to retrieve the values entered into a calendar, or textbox, and how to calculate how many days and/or hours there are between time/date selections from two user controls. If you want to calculate the # days between two user-selected dates then you need two calendar controls, or two textboxes with their .selectionmode set to date or datetime or datetime local, or time (depending on requirement). You can also perform calculations by using the .NOW() funtion which accesses the clock time in your computer. You may begin to wonder how we progressed this far in the class and did not use dates yet in any calculations.Code:Partial Class Timespan_New Inherits System.Web.UI.Page Public Shared gdtTimerStart, gdtTimerEnd As DateTime Public Shared gintNumberWeekDays, gintNumberWeekEnds As Integer Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init 'The page init code runs just once when the webpage is first rendered. This procedure demonstrates how to add hours to the local time on your computer. Did you know the entire People's Republic of China (PRC) uses just one time zone? Beijing time. The built-in function .NOW()works here and in Excel. Change the .to### code after the .NOW function to test out all the different formatting options. Its pretty impressive. Label2.Text = "Pullman " & Now.ToShortDateString & " " & Now.ToShortTimeString Label3.Text = "Beijing time " & Now.AddDays(1).ToShortDateString & " " & Now.AddHours(16).ToShortTimeString 'the following line of code is the supposed fix to maintaining the browser screen position on postback, so the webpage does not jump aound. Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click 'The calendar control is very easy to work with, it is just a bit large for webpages though, and takes up a lot of space. Similar to the .selectedvalue, or .selecteditem.text, the calendar has a .selectedDate property, so its very comfortable to learn and use and is presented here first. The following traps for two errors a) if no date was selected in the calendar, b) if a date was selected in the future. This program requires a .selected date in the past. With Calendar1 If .SelectedDate = Nothing Or .SelectedDate > Today Then TextBox1.Text = "Please select a date in the past" Exit Sub End If End With 'here we create a new variable (ts) of the datatype timespan. Timespan variables can hold the results of time and/or date calculations. As shown, Now() is the way to read the computer's system time. So the next code reads assign to the timespan variable the result of the calculation now minus the date in the past selected in the calendar Dim ts As TimeSpan = Nothing ts = Now.Subtract(Calendar1.SelectedDate) 'there are a lot of different ways to show dates .toshortdate, .tolongdate etc. take a close look at the possibilities. TextBox1.Text = "Today's date captured from dev PC is " & Now.ToShortDateString & vbNewLine & "Calendar selection: " & Calendar1.SelectedDate.ToShortDateString & vbNewLine 'once you have the results of the time or date calculation then you can use it in your logic 'and problem solving. BTW timespan can hold seconds or minutes which can also be analyzed (such as on a website seeing how long a customer looked at a webpage). If ts.Days > 0 Then TextBox1.Text &= "This was " & ts.Days & " days ago." & VbNewLine & VbNewLine ElseIf ts.Days < 0 Then TextBox1.Text &= "This is " & (ts.Days * -1) & " days in the future." & VbNewLine & VbNewLine End If 'notice the timespan is formatted into .totalMinutes, .totalhours, and .days. Pretty straightforward. TextBox1.Text &= "Also calculated as: " & vbNewLine & vbNewLine & ts.TotalMinutes.ToString("N2") & " minutes ago, " _ & vbNewLine & ts.TotalHours.ToString("N2") & " hours ago" & vbNewLine & ts.Days.ToString("N2") & " days ago." End Sub Protected Sub Calendar1_SelectionChanged(sender As Object, e As EventArgs) Handles Calendar1.SelectionChanged 'this is an accounts receivable example. Some customers do not pay on time. This demonstration also shows that you can use a calendar selection event to trigger this code to work. When the program use selects a date in the calendar, that event is noticed by Visual studio. This code runs in response (handles) to that event occuring. 'You can perform data calculations to ascertain the # of days or minutes or hours ago an event happened. There are many situations where it is important to add time as a dimension to your transactions or reporting. Timespan makes this relatively easy. For example you can see how many days ago an invoice was issued If Calendar1.SelectedDate = Nothing Then Exit Sub ' ready the webform TextBox2.Text = Nothing Image2.Visible = False Dim ts As TimeSpan = Now.Subtract(Calendar1.SelectedDate) 'again we place the calculations with dates into the variable called timespan. 'timespan will be used in subsequent programs and within loops, and analyzing databases. The below select case statement within an if:elseif:else:end if statement maybe overkill but is neat and tidy. Yes you can nest one control structure within another. If ts.Days > 0 Then Select Case ts.Days Case Is < 30 'invoice is under 30 days old TextBox2.Text = ts.Days & " days ago - Current invoice" Case 30 To 60 ' invoice is over 30 but less than 60 days old TextBox2.Text = ts.Days & " days past due. Reduce credit to customer. " Case 61 To 90 ' invoice is over 30 but less than 60 days old TextBox2.Text = ts.Days & " days past due. Send dead flowers. " Case Is > 90 'invoice is over 60 days old send the bill collector to talk to the client. TextBox2.Text = ts.Days & " days past due. Send Luca Brasi" ' 'Luca Brasi is a famous bill collector from the movie "The Godfather" Image2.Visible = True Image2.ImageUrl = "luca.gif" End Select ElseIf ts.Days < 0 Then TextBox2.Text = Nothing TextBox2.Text = "This date is in the future, please pick a date in the past" Exit Sub End If 'It is possible to loop a database table and examine all the rows inside the database table and then perhaps identify the invoices that are delinquent (60 or 90 days) and then send a different toned correspondence. A similar scenario is to send a different promotional email based on activity within the prior 60 days. You can perform similar functionality in SQL in group mode, select all the invoices in one time block (say >30 and <60 days) and then kick off some other procedure such as sending them all voicemail or facebook ad. 'or what if you examine the web server logs and identify that a regular customer has not been coming to your gaming website any longer? you can identify these cases and then contact them with a promotional offer. The interesting thing is that you can send out 1 million promotional emails (email marketing) just as eaily as sending out 10. Unfortunately due to past student hanky-panky our class can no longer teach SMTP (email) programming. End Sub Protected Sub Button3_Click(sender As Object, e As System.EventArgs) Handles Button3.Click If Calendar1.SelectedDate = Nothing Then Exit Sub Dim decPrice As Decimal Dim intday, intmonth, intyear As Integer Dim str1, str2, str3, yearmonth As String 'Visual studio dev team has also made it easy to identify what day of ths week or year the transaction is occuring. For example if a retailer has a slow day, you can create a website program to kick-in a 25% discount on for example Wednesdays. 'have you ever noticed the price of airline tickets changes by time of day and day of week? How do they do that? Your humble professor identified that ticket prices change for the same route, based on time of day, and day of week (cheapest flight tickets were before noon on Tuesday am). 'here you can just pull a way to format the date. this would be useful if for example you wanted to create new columns of data for storage to facilitate subsequent analytics (storing the month # or day # as the data goes into the database rather than having to parse it out using DATEPART() in your SQL in subsequent reporting. Here are a sample of the ways you can parcel the data. These are great for using With Calendar1.SelectedDate intday = .Day intmonth = .Month intyear = .Year yearmonth = (intyear * 100) + intmonth 'this formula allows you to draw line charts across an entire dataset very easily. the result is a string fir example 201802, 201803 for February and March of 2018. str1 = .DayOfWeek str2 = .DayOfYear End With 'the below can be written without all the variables, rather just using the calendar1.selecteddate.??? properties. Passing parsed values to variables shown for learning TextBox3.Text = "Month " & intmonth & " Day " & intday & " Year " & intyear & vbNewLine & vbNewLine & "Day of the week is " & str1 & vbNewLine & "This is day number " & str2 & " of year " & intyear & vbNewLine & "This next value is an analysts trick useful to draw linecharts across an entire dataset. Grasshopper memorize this formula and use it to prosper. " & yearmonth Response.Write(Calendar1.SelectedDate.DayOfWeek) 'this is how you can alter a price based on what day of the week it is (making products a little more expensive on the weekends to cover labor costs), you can theoretcally also alter price based on time of day. Perhaps more commonly as a designer of a sales or production system, when you store the transaction into a database you can parse out some numerics about the date. Saving parsed date information eats a little storage space, but speeds up analytics. If you had millions of rows in your stored fact table of transactions, the adding to many extra columns would not be feasible. But if your will need to retrieve records based on filters (such as month or week#) and need to perform complex datetime calculations, the pre-processing of dates can make later calculations run MUCH faster. 'recall we created these 2 global integer variables gintNumberWeekDays, gintNumberWeekEnds Select Case Calendar1.SelectedDate.DayOfWeek Case 0, 6 'these are the weekend days 0 is Sunday, 6 is Saturday decPrice = 7.25 str3 = "Weekend. " gintNumberWeekEnds += 1 Case 1 To 5 'these are the weekdays 1 is Monday, 2 is Tuesday. Yes these are different in the textbox when the selectionmode is date decPrice = 5.75 str3 = "Weekday. " gintNumberWeekDays += 1 End Select TextBox3.Text &= vbNewLine & vbNewLine & str3 & "Charge the customer " & decPrice.ToString("C") txtWeekdayEndTally.Text = "Number transactions weekdays: " & gintNumberWeekDays & vbNewLine & "Number transactions weekdends: " & gintNumberWeekEnds Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub Button4_Click(sender As Object, e As System.EventArgs) Handles Button4.Click 'Here is how you subtract dates or times using 2 calendars, the formula is endtimeControl.selecteddate.subtract(startimecontrol.selecteddate) 'At the top of the we introduced .ADD (.addDays, .addHours) here we show .subtract Dim ts As TimeSpan If Calendar3.SelectedDate = Nothing Or Calendar3.SelectedDate = Nothing Then TextBox4.Text = "please be sure to select a date in both calendays" Exit Sub Else ts = Calendar3.SelectedDate.Subtract(Calendar2.SelectedDate) TextBox4.Text = ts.Days & " days between selections" End If Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub Button5_Click(sender As Object, e As System.EventArgs) Handles Button5.Click DropDownList1.Items.Clear() RadioButtonList1.Items.Clear() 'you can also select a range of dates in a calendar, however you can select a week or a month easily, 'similar to needing to create a listitem to loop thru the items collection of a list control, here we have to create a variable of the datatype datetime. We use this datetime variable to loop thru the selected dates collection. Notice the In statement. That references a collection of dates, for each day in the selecteddates collection. Dim day As DateTime 'this is the variable used to access each item in the dates collection txtDays.Text = Calendar1.SelectedDates.Count & " days Selected" & vbNewLine DropDownList1.Items.Add(Calendar1.SelectedDates.Count & " days") 'Here we fill up the items collection in two list controls (just for variety). For Each day In Calendar1.SelectedDates DropDownList1.Items.Add(day.ToLongDateString()) RadioButtonList1.Items.Add(day.ToShortDateString()) Next Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub Button6_Click(sender As Object, e As System.EventArgs) Handles Button6.Click 'Ok. So we have done a lot with dates, what about hours? 'You can also parse (convert) the time or date typed into a textbox (if its close to being accurate). 'So here is a start of a timekeeping system that a payroll clerk or office manager would use. So a computer consultant is figuring ut how much money to charge on an invoice. This assumes all consulting labor on the job is charged@ $50 per hour. Can you envision a timekeeping system that can collect all the labor for a construction job that incorporates different labor costs? (say painters, electricians, roofers, framers, plumbers, etc.). The DateTIme.Parse is very useful and can read many different ways to type time (7:00, 7:00 AM, 7 AM, etc). Dim ts As TimeSpan ts = DateTime.Parse(TextBox7.Text) - DateTime.Parse(TextBox6.Text) TextBox8.Text = "Hours on the job: " & FormatNumber(ts.TotalHours) & vbNewLine TextBox8.Text &= "Labor charge for the job: " & FormatCurrency(ts.TotalHours * 50) & vbNewLine Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub btnStopwatch_Click(sender As Object, e As System.EventArgs) Handles btnStopwatch.Click 'just grab the current time and save it into a global variable txtElapsedTime.Text = "Timer started..." gdtTimerStart = Now Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub btnFinished_Click(sender As Object, e As System.EventArgs) Handles btnFinished.Click 'create the variable that can hold the data, assign the value to the second variable (end time) which is also captured into a global variable with the value captured from the system clock using the .NOW function. Dim tstimeElapsed As TimeSpan = Nothing gdtTimerEnd = Now 'calculate the elapsed time tstimeElapsed = gdtTimerEnd.Subtract(gdtTimerStart) 'display the elapsed time in minutes and seconds txtElapsedTime.Text = tstimeElapsed.Minutes & " minutes " & tstimeElapsed.Seconds & " seconds" 'reset the variable that can hold the elapsed time tstimeElapsed = Nothing Page.MaintainScrollPositionOnPostBack = True End Sub Protected Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click 'Visual Studio 2013 added new .textmode formatting for a textbox. You can format the textbox to accept dates and time, dates, or time. This procedure mimics the prior demonstration to capture elapsed days between two calendar selections. If txtStartDate.Text = Nothing OrElse txtEndDate.Text = Nothing Then Exit Sub End If Dim ts As TimeSpan ts = DateTime.Parse(txtEndDate.Text) - DateTime.Parse(txtStartDate.Text) txtAnswer.Text = ts.Days & " days between selections" Page.MaintainScrollPositionOnPostBack = True End SubEnd Class ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download