Technique | Data we usually have to process time and date data in programming, which is a relatively difficult type of data because the structure of the time date type is quite complex, and there are certain rules, and if you do not conform to the rules when you define it, the program will go wrong at compile time. In Visual Basic. NET to handle the time date type (Structure) is mainly 2, datetime and TimeSpan respectively, all of which are in the namespace system and in Visual Basic. NET also defines a date of data type that is equivalent to the DateTime class mentioned above. At this time, many friends may ask, what is called structure, what role does it have? In fact, structures and classes are very similar in function and function, and they have constructors, the main differences are as follows:
1. A struct cannot contain an explicit parameterless constructor. Struct members are automatically initialized to their default values.
2. A struct cannot have an initializer with the following form: base.
In fact, for most friends, when you use structures and classes specifically, you don't have to take into account the differences, because they are almost identical in use.
Although Visual Basic. NET provides the date data type to handle the time date type, but it is often not used in practice because it is very cumbersome to define, coupled with the complexity of the time-date type structure, which often leads to errors for many beginners. The following is in visual Basic. NET defines a time date type data variable by a date data type, it is visible that it tumultuous:
Dim s as Date = #12/2/2002 7:00:00 pm#
When defining date data types, you must be aware of the following three points:
1. The date value must be enclosed in the number sign "#".
2. Date data in dates value is optional, if any must conform to the format "m/d/yyyy".
3. The time data in the date value is optional, if the date data must be separated by a space, and the minutes and seconds are separated by ":".
A The relationship and distinction between DateTime and TimeSpan:
DateTime and TimeSpan are visual Basic. NET, the difference is that dattime represents a fixed time, and timespan represents a time interval, that is, a period of time. In the program example described below, the timespan is used for the difference between the current time and the given time.
Two Common members in DateTime and TimeSpan and their descriptions:
The datetime structure and the timespan structure provide rich methods and properties that can be used to handle almost any time date type data directly. Tables 01 and 02, respectively, are common properties and common methods for datetime structures and their descriptions:
The attribute description date gets the date part of this instance. Day gets the date represented by this instance as the day ordinal of the month. DayOfWeek gets the day of the week that this instance represents. DayOfYear gets the date represented by this instance is the day ordinal of the year. Hour gets the hour portion of the date represented by this instance. Millisecond gets the millisecond portion of the date represented by this instance. Minute gets the minute portion of the date represented by this instance. Month gets the month portion of the date represented by this instance. Now creates a DateTime instance, which is the current local date and time on this computer. Second gets the second portion of the date represented by this instance. TimeOfDay gets the time of the day for this instance. Today gets the current date. Year gets the years portion of the date represented by this instance. Common Properties of Table 01:datetime classes and their descriptions
Method Description Add adds the value of the specified timespan to the value of this instance. AddDays adds the specified number of days to the value of this instance. AddHours adds the specified number of hours to the value of this instance. Addmilliseconds adds the specified number of milliseconds to the value of this instance. AddMinutes adds the specified number of minutes to the value of this instance. Addmonths adds the specified number of months to the value of this instance. AddSeconds adds the specified number of seconds to the value of this instance. Addyears adds the specified number of years to the value of this instance. DaysInMonth returns the number of days of the specified month in the specified year. Isleapyear returns whether the specified year is an indication of leap years. Parse converts the specified string representation of a date and time to its equivalent datetime instance. Subtract subtracts the specified time or duration from this instance. Tolongdatestring converts the value of this instance to its equivalent long date string representation. Tolongtimestring converts the value of this instance to its equivalent long time string representation. Toshorttimestring converts the value of this instance to its equivalent short time string representation. ToShortDateString converts the value of this instance to its equivalent short date string representation.
The common method of table 02:datetime structure and its explanation
Tables 03 and 04, respectively, are common properties and common methods for timespan structures and their descriptions:
Property Description Day Gets the number of days represented by this instance. Hours gets the whole number of hours represented by this instance. Milliseconds gets the whole number of milliseconds represented by this instance. Minutes gets the whole number of minutes represented by this instance. Seconds gets the whole number of seconds represented by this instance. Ticks gets the value of this instance represented by a scale. Totaldays gets the value of this instance, expressed as a decimal part of the whole day and day. Totalhours Gets the value of this instance, represented by the decimal portion of the whole hour and hour. TotalMilliseconds gets the value of this instance as an integer millisecond and a fractional part of the millisecond. Totalminutes Gets the value of this instance as an integer minute and a decimal part of the minute. TotalSeconds Gets the value of this instance as an integer second and a decimal part of the second. Common Properties of Table 03:timespan structure and its description
Method Description Add adds the specified timespan to this instance. Duration returns the timespan for the absolute value of this instance. Fromdays returns the TimeSpan that represents the specified number of days, where the specified number of days is accurate to the nearest millisecond. Fromhours returns the TimeSpan that represents the specified number of hours, where the number of hours is specified to the nearest millisecond. Frommilliseconds returns the TimeSpan that represents the specified number of milliseconds. Fromminutes returns the TimeSpan that represents the specified number of minutes, in which the specified number of minutes is accurate to the nearest millisecond. FromSeconds returns the TimeSpan that represents the specified number of seconds, where the specified number of seconds is accurate to the nearest millisecond. Subtract subtracts the specified timespan from this instance.
The common method of table 04:timespan structure and its explanation
Three Methods of usage of common members in DateTime and TimeSpan and their use techniques:
After you know the common methods and common properties of datetime and TimeSpan, here's an example to learn how to use these methods and properties. In the following example, the following methods are highlighted:
1. Judge the legality of the date time string entered.
2. The operation between DateTime instances.
3. Date-Time data acquisition method.
The following is in visual Basic. NET implementation of the above features, the main steps of the example:
1. Start visual Studio. Net.
2. Select Menu "File" | "new" | "Project", pop-up the "New Project" dialog box.
3. Set the project type to Visual basic project.
4. Set "template" to "Windows Application".
5. In the Name text box, enter process date time data.
6. In the "Position" text box, enter "E:\VS." NET project, and then click the OK button, so that in the E:\VS. NET project directory, a folder called "Process Date Time data" is created, and a project file named "Process datetime data" is generated inside.
7. Take visual Studio. NET to the Form1.vb window, and from the Windows Forms Components tab in the Toolbox, drag the following components into the Form1 form and perform the appropriate actions:
A TabControl component.
Three TabPage components.
19 Label components.
19 TextBox component to display the time date value.
Three button components, respectively, Button1 to Button3, and after the three button components are dragged into the Form1 design form, double-click the three components, so that the system will produce the processing code corresponding to the click time of the three components in the Form1.vb file respectively.
8. Set the main properties of the component according to Figure 01, figure 02, Figure 03:
Figure 01: One of the "process date-time data" design interfaces
Figure 02: "Process Date Time data" Design Interface II
Figure 03: "Process Date Time data" design interface Three
After completing the above work, the following is to enter the functional implementation phase of the program.
9. Judge the legality of the date time string entered. In order to achieve this function, first of all to master the input date time string into the available for visual Basic. NET uses a method of date-time type data. This approach is to use the parse method in DateTime, Parse method can convert a date-time string into a DateTime instance. The following is a specific conversion code:
Dim dttemp as System.DateTime = System.DateTime.Parse ("12/2/2002 13:20:25")
However, if the string you want to convert is not legitimate, the program will appear unexpectedly when it executes. The program uses the capture of the exception to determine the legitimacy of the string given to be converted. In Visual Basic. NET to catch an exception in general use a try ... Catch .... End Try statement. Note Here is a try ... Catch .... The end Try statement is a very important statement that is frequently used in many of the key code sections in later chapters, and it does solve a lot of troublesome problems.
Here are the steps to implement this feature in this program:
First take visual Studio. NET's current window switches to "Form1.vb" and enters the editing interface of the Form1.vb file. Then replace the processing code for the Click event for the Button3 component in Form1.vb with the following code.
Private Sub button3_click (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button3.click
Dim Dtmydate as System.DateTime
Try
Dtmydate = DateTime.Parse (Textbox19.text)
' Converts a given date-time string
Catch
MessageBox.Show ("The time date string entered is not legal!") "," the mistake! " )
' Prompt for error
Textbox19.text = ""
Return
End Try
' Above is a typical code to determine the legality of the input date-time string
End Sub
10. Get the computer date time data. The program to achieve this function is very simple, only need to master Table 01 and Table 02 of the commonly used properties of the DateTime, methods of using the method can be easily completed. Specific to this program is to replace the following code in Form1.vb Button2 click event corresponding processing code:
Private Sub button1_click (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button1.Click
Dim dmydate as DateTime = DateTime.Now
' Create an instance where this instance holds the current date and time
TextBox1.Text = dmydate.tostring ()
' Show current date and time
TextBox2.Text = Dmydate.date
' Show current date
TextBox3.Text = Dmydate.year
' Show year
Textbox4.text = Dmydate.month
' Show month
Textbox5.text = Dmydate.day
' Show the day number
Textbox6.text = Dmydate.dayofyear
' Show the current day is the number of days of the year
Textbox7.text = Dmydate.dayofweek
' Show the current day is the number of days of the week
Textbox8.text = dmydate.tolongdatestring
' Display date as a long date
Textbox9.text = dmydate.toshortdatestring
' Display date as a short date
Textbox18.text = dMyDate.TimeOfDay.ToString ()
' Show Current time
Textbox17.text = Dmydate.hour
' Show hours for current time
Textbox16.text = Dmydate.minute
' Minutes to display the current time
Textbox15.text = Dmydate.second
' Seconds to display the current time
Textbox14.text = Dmydate.millisecond
' Show milliseconds for current time
Textbox13.text = dmydate.tolongtimestring
' Displays the current time in a long time form
Textbox12.text = dmydate.toshorttimestring
' Displays the current time in a short time form
End Sub
11. Date-time data operations. The code described below is the difference between implementing two DateTime instances, the current time and the given time difference. The solution is to first determine the legality of the given date-time string, if not legitimate, and return. If it is legitimate, then create a DateTime instance dtmydate. Then Dtmydate calls its subtract method minus the current time and holds it to the TimeSpan instance tstemp. Tstemp calls its duration method to show the absolute value of the difference between the two. The implementation method in the program is to replace the handling code of the Button2 click event in Form1.vb with the following code:
Private Sub button2_click (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button2.click
Dim Tstemp as TimeSpan
Dim Dtmydate as DateTime
Try
Dtmydate = DateTime.Parse (Textbox10.text)
Catch
MessageBox.Show ("The time date string entered is not legal!") "," the mistake! " )
Return
End Try
' Judge the legality of the time date string entered
Tstemp = Dtmydate.subtract (DateTime.Now)
' Two datetime instances subtracted
Textbox11.text = tsTemp.Duration.ToString ()
' Take the difference in absolute value of two datetime and show it
End Sub
At this point, all the work on the process datetime data project is complete after the steps have been executed correctly and saved successfully. Figure 04, Figure 05, and figure 06 are the compiled running interfaces of the process date Time data project:
Figure 04: One of the "process date-time data" runtime interfaces
Figure 05: "Process Date Time data" Run interface two
Figure 06: "Process Date Time data" running interface three
Four Summary:
This article describes in Visual Basic. NET, the processing method of date time type data and some considerations and techniques in processing these data. The following are the points of knowledge in this article:
1. The difference between structure and class.
2. Define datetime with date variable, and its considerations.
3. The main differences between DateTime and TimeSpan, and the main members of the two and their brief descriptions.
4. Judge the legality of a given time date.
5. Date-Time type data (datetime instance) operation.
6. Date time and its related numerical data acquisition.
If you have mastered the above content through the introduction of this article, the purpose of this article even if completed, let us see the next section!