CyberiaPC.com Main Page




Learning VB

Manipulating Strings and Integers

There are many small things that can be done to data types (integers, strings...) in VB that make the life of the programmer much easier.  In this section, I'll discuss the most important and the most widely used techniques for manipulating numbers and characters.  Here is an index of what will be discussed in this lesson:

 
Converting Data Types
Constants
Dates and Times
Using the Format Function
Manipulating Text Strings

Dates and Times

In Visual Basic, it is extremely easy to perform calculations with dates and times.  This is because of the fact that dates and times are stored internally as numbers, which means that if you added 2 to today's date, the date would change to that of the day after tomorrow.  Declaring a Date variable is done by simply choosing Date as the data type:

     Dim ExamDay As Date
     Dim TodayDate As Date

     TodayDate = Date
     ExamDay = TodayDate + 20

The first two lines declare our date variables.  The third line set's today's date to the system date (there are two functions in VB: Date and Time that can used to set variables to the current date and time, respectively.  Also, you can use Now to set the current date and time!)  The last line sets the ExamDay date to 20 days from today.  Simple enough?

Here are some useful date/time functions used for displaying parts of values:

Function Example
Year() Year(Now)
Month() Month(Now)
Day() Day(Now)
Weekday() Weekday(Now)
Hour() Hour(Now)
Minute() Minute(Now)
Second() Second(Now)

You may also want to use the DateDiff function.  This function displays the difference between two dates.  For example:

     Dim Date1 As Date
     Dim Date2 As Date
     Dim Difference As String

     Date1 = Date
     Date2 = 12 / 31 / 2030
     Difference = DateDiff("d", Date2, Date1)

     MsgBox Difference

I want to remind you (if you forgot) that the variables go in the General Declarations section whereas the rest of the code goes into whichever procedure you'd like it to be invoked in.

In the above example, Date1 holds today's date and Date2 hold another date.  The difference is stored in the variable Difference and then displayed.  Note that the syntax for the DateDiff function is fairly simply.  You enter the interval that you want to calculate the difference in, and then your two dates.  Here is a list of intervals that you could use:

Interval Example
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
m Minute
s Second

{Go Back To VB Lessons Page}