Scripting QTP - CH14 - DotNet
Scripting QTP - CH14 - DotNet
DOTNETFACTORY .................................................................................................................... 4
DotNetFactory
Enables you to create an instance of a .NET object, and access its methods and
properties.
You can use this object to access the static methods and properties of a class that
does not have an instance constructor, for example, System.Environment, as well as
a class that does.
CreateInstance Method
If you want to use a .NET object as an argument for a method in QuickTest, you
must first create a COM interface for the .NET object using the CreateInstance
method. Then you pass that interface as the method argument.
Set var_CreateInstance =
DotNetFactory.CreateInstance (TypeName [,Assembly] [,args])
Parameter Description
The full name of the object type, for example,
TypeName
System.Windows.Forms.Form.
Optional. If the assembly is preloaded in the registry, you do not need to
enter it. Otherwise, you should enter the full path name, for example,
System.Windows.Forms. If you want to create an instance of a type in the
GAC (Global Assembly Cache), you can enter the short name, for example,
Assembly Forms.
Note: If you do not pass this argument, QuickTest assumes that the
assembly is resident in memory. If QuickTest does not find the assembly,
an error message is displayed during the run session.
Optional. The required arguments, if any, for the specified TypeName
args
and/or Assembly
QTP DotNetFactory
When QTP version 9.0 was released. I have noticed that a new utility object was added,the
DotNetFactory object.
Since, that period of time, I was working on a web application, I thought myself , that
DotNetFactory is a utility to work with .NET applications, like the DOT.NET Extensibility
In QTP Version 9.2, I so the following example in the QTP help
Set var_CreateInstance = _
DotNetFactory.CreateInstance("System.Windows.Forms.Form", "System.Windows.Forms")
var_CreateInstance.Show
wait 2
var_CreateInstance.Close
And also
Set var_CreateInstance = DotNetFactory.CreateInstance("System.Environment")
msgbox var_CreateInstance.CurrentDirectory
The first example display an empty windows form. I started to think, why I need to display
a form , during a test run. The second example catch my eye, and when I tried it in qtp, I
got the following result :
"wow!!" I said to my self, nice to know that I can have every single environment value of
the system, especially SystemDirectory property. The others values, can be retrieved using
standard VBScript objects and QTP Environment object. So, again … I did not paid attention
and full research for the dot.net factory.
One month later, I add an issue when testing a financial application.
The application ( web based ) shows the interests to pay for each month. Because the
application is a bank system application, I can't show screenshots. But a web table was
displayed in the following format :
Date Amount
Tue, 12 Sep 2006 2500$
Thu, 12 Oct 2006 2490$
Sun, 12 Nov 2006 2475$
Tue, 12 Dec 2006 2466$
My problem here, were the dates. VBScript doesn't able to convert formats, to the specific
format I needed, and beside this, any user can change the display format to : mm/dd/yyyy
or mmddyy or dd\mm\yy etc.
dteDate = Cdate( "Tue, 12 Sep 2006" )
Because the CDate conversion error, in pure vbscript I need a function like the
follows
Option Explicit
Dim arr1, arr2, MyDate, nMonth, dteDate
MyDate = Browser("B").Page("P").WebTable("rates").GetCellData(1,1)
arr1 = Split( MyDate, "," )
arr2 = Split( arr1(1), " " )
Select Case arr2(2)
Case "Jan" : nMonth = 1
Case "Feb" : nMonth = 2
Case "Mar" : nMonth = 3
Case "Apr" : nMonth = 4
Case "May" : nMonth = 5
Case "Jun" : nMonth = 6
Case "Jul" : nMonth = 7
Case "Aug" : nMonth = 8
Case "Sep" : nMonth = 9
Case "Oct" : nMonth = 10
Case "Nov" : nMonth = 11
Case "Dec" : nMonth = 12
End Select
dteDate = DateSerial(arr2(3), nMonth, arr2(1))
msgbox dteDate
This process only to retrieve the first date, than, I have to use the DateAdd function, and
another function to convert the new date, to the desired format.
As you can see, this is a lot of work, beside, that the user can change the formats.
The application has hundreds of date fields, and dates fields are very critical for the
application.
From this moment I start to make a research, to find a simplest and elegant solution.
I found the System.DateTime object in the MSDN DOT.NET help, and remember
immediately of the QTP example about the System.Environment object
So I tried the follow :
Option Explicit
Dim DateTime
Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" )
A little more research, using the MSDN help I got the ultimate date handling functionality
Option Explicit
Dim DateTime, SystemDateTime, i, Str
Set SystemDateTime = DotNetFactory.CreateInstance( "System.DateTime" )
Set DateTime = SystemDateTime.Parse( "Tue, 12 Sep 2006" )
For i = 1 To 12
So, the conclusion of all my research, is that you can use almost any DOT.NET object
supported by your Dot.Net Framework ( today is version 3 ) , so this chapter of
DotNetFactory will demonstrate only the System.DateTime and System.TimeSpan
classes. In some examples I use The System.Text.TextBuilder class,
System.Globalization.CultureInfo class, System.DateTimeKind Enumerator,
System.Globalization.Calendar and more
System.DateTime Structure
System.DateTime Fields
Name Description
MaxValue Represents the largest possible value of DateTime. This field is read-only.
MinValue Represents the smallest possible value of DateTime. This field is read-only
DateTime.MaxValue Field
DateTime.MinValue Field
System.DateTime Contructors
DateTime (Int32, Int32, Int32, Initializes a new instance of the DateTime structure
Int32, Int32, Int32, Int32, to the specified year, month, day, hour, minute,
DateTimeKind) second, millisecond, and Coordinated Universal Time
(UTC) or local time.
Initializes a new instance of the DateTime structure
DateTime (Int32, Int32, Int32,
to the specified year, month, day, hour, minute,
Int32, Int32, Int32, Int32,
second, millisecond, and Coordinated Universal Time
Calendar, DateTimeKind)
(UTC) or local time for the specified calendar.
Parameter Description
ticks A date and time expressed in 100-nanosecond units.
System.DateTime object
format = "{0}) The {1} date and time is {2:MM/dd/yyyy hh:mm:ss tt}{3}"
Set SDT = DotNetFactory.CreateInstance( "System.DateTime" )
' ** Create a DateTime for the maximum date and time using ticks
Set dtMax = DotNetFactory.CreateInstance( "System.DateTime", , SDT.MaxValue.Ticks )
' ** Create a DateTime for the minimum date and time using ticks.
Set dtMin = DotNetFactory.CreateInstance( "System.DateTime", , SDT.MinValue.Ticks )
' ** Create a custom DateTime for 7/28/1979 at 10:35:05 PM using a calendar based on
' the "en-US" culture, and ticks.
Set CI = DotNetFactory.CreateInstance( _
"System.Globalization.CultureInfo", _
"System", "en-US", False _
)
Set ticks = DotNetFactory.CreateInstance( _
"System.DateTime", ,1979, 7, 28, 22, 35, 5, CI.Calendar _
).Ticks
Set dtCustom = DotNetFactory.CreateInstance( "System.DateTime", , ticks )
' ** Reporting
Set SB = DotNetFactory.CreateInstance( "System.Text.StringBuilder" )
SB.AppendFormat format, 1, "maximum", dtMax, vbNewLine
SB.AppendFormat format, 2, "minimum", dtMin, vbNewLine
SB.AppendFormat format, 3, "custom", dtCustom, vbNewLine
SB.AppendFormat "The custom datetime is created from {0:N0} ticks.", ticks
Initializes a new instance of the DateTime structure to a specified number of ticks and
to Coordinated Universal Time (UTC) or local time.
Set object =
DotNetFactory.CreateInstance( "System.DateTime", , ticks, kind )
Parameter Description
ticks A date and time expressed in 100-nanosecond units.
One of the DateTimeKind values that indicates whether ticks specifies a
kind
local time, Coordinated Universal Time (UTC), or neither.
System.DateTime object
The following code example uses the SpecifyKind method to demonstrate how the Kind
property influences the ToLocalTime and ToUniversalTime conversion methods.
Option Explicit
Const DATE_PATTERN = "M/d/yyyy hh:mm:ss tt"
Dim DateTime, saveNow, saveUtcNow, myDt
Dim DateTimeKind
' ** Get the date and time for the current moment, adjusted to the local time zone.
Set saveNow = DateTime.Now
' ** Get the date and time for the current moment expressed as coordinated universal
' time (UTC).
Set saveUtcNow = DateTime.UtcNow
' ** Display the value and Kind property of the current moment expressed as UTC and
' local time.
Call DisplayNow( "UtcNow: ..........", saveUtcNow )
Call DisplayNow( "Now: .............", saveNow )
' ** Change the Kind property of the current moment to DateTimeKind.Utc and display
' the result.
Set DateTimeKind = DotNetFactory.CreateInstance( "System.DateTimeKind" )
' ** Change the Kind property of the current moment to DateTimeKind.Local and ' '
' display the result.
Set myDt = DateTime.SpecifyKind( saveNow, DateTimeKind.Local )
Call Display( "Local: ...........", myDt )
' ** Change the Kind property of the current moment to DateTimeKind.Unspecified and
' display the result.
Set myDt = DateTime.SpecifyKind( saveNow, DateTimeKind.Unspecified )
Call Display( "Unspecified: .....", myDt )
Set myDt = Nothing : Set DateTimeKind = Nothing : Set DateTime = Nothing
Set saveNow = Nothing : Set saveUtcNow = Nothing
Initializes a new instance of the DateTime structure to the specified year, month, and
day.
Set object =
DotNetFactory.CreateInstance( "System.DateTime", , year, month, day )
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
ArgumentException - The specified parameters evaluate to less than MinValue or
more than MaxValue.
The following code example uses the SpecifyKind method to demonstrate how the Kind
property influences the ToLocalTime and ToUniversalTime conversion methods.
Option Explicit
Dim DateTime
Initializes a new instance of the DateTime structure to the specified year, month, and
day for the specified calendar.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
Day The day (1 through the number of days in month).
calendar The Calendar that applies to this DateTime.
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
ArgumentException - The specified parameters evaluate to less than MinValue or
more than MaxValue.
The time of day for the resulting DateTime is midnight (00:00:00). The Kind
property is initialized to Unspecified
The allowable values for year, month, and day depend on calendar. An exception is
thrown if the specified date and time cannot be expressed using calendar.
The System.Globalization namespace provides several calendars including
GregorianCalendar and JulianCalendar.
The following code example uses the SpecifyKind method to demonstrate how the Kind
property influences the ToLocalTime and ToUniversalTime conversion methods.
Option Explicit
Dim DateTime
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, and second.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
ArgumentException - The specified parameters evaluate to less than MinValue or
more than MaxValue.
Set DateTime = _
DotNetFactory.CreateInstance( "System.DateTime", ,1979, 7, 28, 12, 23, 32 )
Print DateTime.ToString
Print DateTime.ToString( "F" )
Print DateTime.ToString( "R" )
Print DateTime.ToString( "G" )
Set DateTime = Nothing
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, and second for the specified calendar.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
minute The minutes (0 through 59).
second The seconds (0 through 59).
calendar The Calendar that applies to this DateTime.
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
ArgumentException - The specified parameters evaluate to less than MinValue or
more than MaxValue.
ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, second, and Coordinated Universal Time (UTC) or local time.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
minute The minutes (0 through 59).
second The seconds (0 through 59).
One of the DateTimeKind values that indicates whether year, month,
kind day, hour, minute and second specify a local time, Coordinated
Universal Time (UTC), or neither.
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
ArgumentException
The specified parameters evaluate to less than MinValue or more than
MaxValue.
Kind is not one of the DateTimeKind values.
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, second and millisecond
Set object =
DotNetFactory.CreateInstance( "System.DateTime", , _
year, month, day, hour, minute, second, millisecond )
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
minute The minutes (0 through 59).
second The seconds (0 through 59).
millisecond The milliseconds (0 through 999).
System.DateTime object
ArgumentOutOfRangeException.
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
millisecond is less than 0 or greater than 999.
ArgumentException
The specified parameters evaluate to less than MinValue or more than
MaxValue.
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, second, and millisecond for the specified calendar.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
minute The minutes (0 through 59).
second The seconds (0 through 59).
millisecond The milliseconds (0 through 999).
calendar The Calendar that applies to this DateTime.
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
millisecond is less than 0 or greater than 999.
ArgumentException - The specified parameters evaluate to less than MinValue or
more than MaxValue.
ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local
time.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
minute The minutes (0 through 59).
second The seconds (0 through 59).
millisecond The milliseconds (0 through 999).
One of the DateTimeKind values that indicates whether year, month,
kind day, hour, minute, second, and millisecond specify a local time,
Coordinated Universal Time (UTC), or neither.
System.DateTime object
ArgumentOutOfRangeException .
year is less than 1 or greater than 9999
month is less than 1 or greater than 12.
day is less than 1 or greater than the number of days in month.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
millisecond is less than 0 or greater than 999.
ArgumentException
The specified parameters evaluate to less than MinValue or more than
MaxValue.
Kind is not one of the DateTimeKind values.
Initializes a new instance of the DateTime structure to the specified year, month, day,
hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local
time for the specified calendar.
Parameter Description
year The year (1 through 9999).
month The month (1 through 12).
day The day (1 through the number of days in month).
hour The hours (0 through 23).
minute The minutes (0 through 59).
second The seconds (0 through 59).
millisecond The milliseconds (0 through 999).
calendar The Calendar object that applies to this DateTime.
One of the DateTimeKind values that indicates whether year, month,
kind day, hour, minute, second, and millisecond specify a local time,
Coordinated Universal Time (UTC), or neither.
System.DateTime object
ArgumentOutOfRangeException .
year is not in the range supported by calendar.month is less than 1 or greater
than 12.
month is less than 1 or greater than the number of months in calendar.
day is less than 1 or greater than the number of days in month.hour is less than
0 or greater than 23.
hour is less than 0 or greater than 23.
minute is less than 0 or greater than 59.
second is less than 0 or greater than 59.
millisecond is less than 0 or greater than 999.
ArgumentException
The specified parameters evaluate to less than MinValue or more than MaxValue.
kind is not one of the DateTimeKind values.
ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
The allowable values for year, month, and day parameters depend on the calendar
parameter. An exception is thrown if the specified date and time cannot be
expressed using calendar.
The System.Globalization namespace provides several calendars including
GregorianCalendar and JulianCalendar.
DateTime Properties
Name Description
Date Gets the date component of this instance.
Day Gets the day of the month represented by this instance.
DayOfWeek Gets the day of the week represented by this instance.
DateTime.Date Property
object.Date
A new DateTime with the same date as this instance, and the time value set to 12:00:00
midnight (00:00:00).
DateTime.Day Property
Value = object.Date
DateTime.DayOfWeek Property
Value = object.DayOfWeek
A DayOfWeek enumerated constant that indicates the day of the week. This property
value ranges from zero, indicating Sunday, to six, indicating Saturday.
DateTime.DayOfYear Property
object.DayOfYear
The following example returns the Day of The year for Today
Msgbox DotNetFactory.CreateInstance( "System.DateTime" ).Today.DayOfYear
DateTime.Hour Property
object.Hour
DateTime.Kind Property
Gets a value that indicates whether the time represented by this instance is based on
local time, Coordinated Universal Time (UTC), or neither.
object.Kind
The following example uses Item to retrieve the FolderItem object representing the
Windows folder and filtering the content
Option Explicit
Dim saveNow, saveUtcNow, myDt
Dim DateTimeKind
DateTime.Millisecond Property
Value = object.Millisecond
DateTime.Minute Property
Value = object.Minute
DateTime.Month Property
Value = object.Month
DateTime.Now Property
Gets a DateTime object that is set to the current date and time on this computer,
Value = object.Now
DateTime.Second Property
Value = object.Second
DateTime.Ticks Property
Gets the number of ticks that represent the date and time of this instance
Value = object.Ticks
The number of ticks that represent the date and time of this instance. The value is
between MinValue and MaxValue.
DateTime.TimeOfDay Property
Value = object.TimeOfDay
A TimeSpan that represents the fraction of the day that has elapsed since midnight.
The following example uses Item to retrieve the FolderItem object representing the
Windows folder and filtering the content
Option Explicit
Dim saveNow, timeSpan
DateTime.Today Property
Value = object.Today
A DateTime set to today's date, with the time component set to 00:00:00.
DateTime.UtcNow Property
Gets a DateTime object that is set to the current date and time on this computer,
expressed as the Coordinated Universal Time (UTC).
Value = object.UtcNow
Starting with the .NET Framework version 2.0, the return value is a DateTime whose
Kind property returns Utc.
DateTime.Year Property
Value = object.Year
DateTime Methods
Name Description
Adds the value of the specified TimeSpan to the value of this
Add
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.
Adds the specified number of milliseconds to the value of this
AddMilliseconds
instance.
Adds the specified number of minutes to the value of this
AddMinutes
instance.
Adds the specified number of months to the value of this
AddMonths
instance.
Adds the specified number of seconds to the value of this
AddSeconds
instance.
AddTicks Adds the specified number of ticks to the value of this instance.
AddYears Adds the specified number of years to the value of this instance.
Compares two instances of DateTime and returns an indication of
Compare
their relative values.
Overloaded. Compares this instance to a specified object or value
CompareTo
type and returns an indication of their relative values.
DaysInMonth Returns the number of days in the specified month and year.
are equal.
Adds the value of the specified TimeSpan to the value of this instance.
Parameter Description
value A TimeSpan that contains the interval to add.
A DateTime whose value is the sum of the date and time represented by this instance
and the time interval represented by value.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
The following code example demonstrates the Add method. It calculates the day of the
week that is 36 days (864 hours) from this moment.
Option Explicit
Dim saveNow, duration, answer
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
The fractional part of value is the fractional part of a day. For example, 4.5 is
equivalent to 4 days, 12 hours, 0 minutes, 0 seconds, 0 milliseconds, and 0 ticks.
The value parameter is rounded to the nearest millisecond.
Parameter Description
A number of whole and fractional days. The value parameter can be
days
negative or positive
A DateTime whose value is the sum of the date and time represented by this instance
and the number of days represented by days
Parameter Description
number of whole and fractional hours. The value parameter can be
hours
negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance
and the number of hours represented by hours.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
The fractional part of value is the fractional part of an hour. For example, 4.5 is
equivalent to 4 hours, 30 minutes, 0 seconds, 0 milliseconds, and 0 ticks..
The value parameter is rounded to the nearest millisecond.
Parameter Description
A DateTime whose value is the sum of the date and time represented by this instance
and the number of milliseconds represented by value.
This method does not change the value of this DateTime. Instead, a new
DateTime is returned whose value is the result of this operation.
The fractional part of value is the fractional part of a millisecond. For example, 4.5 is
equivalent to 4 milliseconds, and 5000 ticks, where one millisecond = 10000 ticks.
The value parameter is rounded to the nearest millisecond.
Parameter Description
A number of whole and fractional minutes. The value parameter can be
minutes
negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance
and the number of minutes represented by minutes.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
The fractional part of value is the fractional part of a minute. For example, 4.5 is
equivalent to 4 minutes, 30 seconds, 0 milliseconds, and 0 ticks.
The value parameter is rounded to the nearest millisecond.
Parameter Description
months A number of months. The months parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance
and months.
ArgumentOutOfRangeException
months is less than -120,000 or greater than 120,000.
The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new
DateTime is returned whose value is the result of this operation.
The AddMonths method calculates the resulting month and year, taking into
account leap years and the number of days in a month, then adjusts the day part of
the resulting DateTime object. If the resulting day is not a valid day in the resulting
month, the last valid day of the resulting month is used. For example, March 31st +
1 month = April 30th. The time-of-day part of the resulting DateTime object
remains the same as this instance.
Parameter Description
A number of whole and fractional seconds. The value parameter can be
seconds
negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance
and the number of seconds represented by seconds.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
A The fractional part of value is the fractional part of a second. For example, 4.5 is
equivalent to 4 seconds, 500 milliseconds, and 0 ticks.
The value parameter is rounded to the nearest millisecond.
Parameter Description
A number of 100-nanosecond ticks. The value parameter can be positive
ticks
or negative.
A DateTime whose value is the sum of the date and time represented by this
instance and the time represented by ticks.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
Parameter Description
years A number of years. The value parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance
and the number of years represented by years.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation.
The AddYears method calculates the resulting year taking into account leap years.
The month and time-of-day part of the resulting DateTime object remains the same
as this instance.
Compares two instances of DateTime and returns an indication of their relative values.
Parameter Description
dt1 The first DateTime.
dt2 The second DateTime.
Before comparing DateTime objects, insure that the objects represent times in the
same time zone.
Compares this instance to a specified DateTime object and returns an indication of their
relative values.
instance.CompareTo( value )
Parameter Description
value A DateTime object to compare.
A signed number indicating the relative values of this instance and the value parameter.
Less than zero - This instance is less than value
Zero - This instance is equal to value.
Greater than zero - This instance is greater than value.
Before comparing DateTime objects, insure that the objects represent times in the
same time zone.
Parameter Description
year The year.
month The month (a number ranging from 1 to 12).
The number of days in month for the specified year. For example, if month equals 2
for February, the return value is 28 or 29 depending upon whether year is a leap
year.
ArgumentOutOfRangeException
month is less than 1 or greater than 12.
year is less than 1 or greater than 9999.
Returns a value indicating whether this instance is equal to the specified DateTime
instance.
Parameter Description
value A DateTime instance to compare to this instance.
true if the value parameter equals the value of this instance; otherwise, false.
Parameter Description
t1 The first DateTime instance.
t2 The second DateTime instance.
Deserializes a 64-bit binary value and recreates an original serialized DateTime object
instance.FromBinary( dateData )
Parameter Description
A 64-bit signed integer that encodes the Kind property in a 2-bit field
dateData
and the Ticks property in a 62-bit field
A DateTime object that is equivalent to the DateTime object that was serialized by
the ToBinary method
Use the ToBinary method to convert the value of the current DateTime object to a
binary value. Subsequently, use the binary value and the FromBinary method to
recreate the original DateTime object.
A local time, which is a Coordinated Universal Time adjusted to the local time zone,
is represented by a DateTime structure whose Kind property has the value Local. If
a local DateTime object is serialized in one time zone by the ToBinary method and
deserialized in a different time zone by the FromBinary method, the local time
represented by the resulting DateTime object is automatically adjusted to the
second time zone.
For example, consider a DateTime object that represents a local time of 3 P.M. An
application executing in a western time zone uses the ToBinary method to convert
that DateTime object to a binary value, then another application executing in a time
zone three hours east of the original one uses the FromBinary method to convert
the binary value to a new DateTime object. The value of the new DateTime object
is 6 P.M., which represents the same point in time as the original 3 P.M. value, but is
adjusted to local time in the eastern time zone.
Parameter Description
fileTime A Windows file time expressed in ticks.
A DateTime object that represents a local time equivalent to the date and time
represented by the fileTime parameter.
A Windows file time is a 64-bit value that represents the number of 100-nanosecond
intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.)
Coordinated Universal Time (UTC). Windows uses a file time to record when an
application creates, accesses, or writes to a file.
The fileTime parameter specifies a file time expressed in 100-nanosecond ticks.
Starting with the .NET Framework version 2.0, the return value is a DateTime
whose Kind property is Local.
Parameter Description
fileTime A Windows file time expressed in ticks.
A DateTime object that represents a UTC time equivalent to the date and time
represented by the fileTime parameter
A Windows file time is a 64-bit value that represents the number of 100-nanosecond
intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.)
Coordinated Universal Time (UTC). Windows uses a file time to record when an
application creates, accesses, or writes to a file.
The fileTime parameter specifies a file time expressed in 100-nanosecond ticks.
Starting with the .NET Framework version 2.0, the return value is a DateTime
whose Kind property is Utc.
DateTime.GetTimeFormats Method
Name Description
Converts the value of this instance to all the string
GetTimeFormats() representations supported by the standard DateTime
format specifiers.
Converts the value of this instance to all the string
DateTime.GetDateTimeFormats
representations supported by the specified standard
(Char)
DateTime format specifier.
Converts the value of this instance to all the string
DateTime.GetDateTimeFormats representations supported by the standard DateTime
(IFormatProvider) format specifiers and the specified culture-specific
formatting information.
Converts the value of this instance to all the string
DateTime.GetDateTimeFormats representations supported by the specified standard
(Char, IFormatProvider) DateTime format specifier and culture-specific
formatting information.
DateTime.GetTimeFormats () Method
Converts the value of this instance to all the string representations supported by the
standard DateTime format specifiers.
A string array where each element is the representation of the value of this instance
formatted with one of the standard DateTime formatting specifiers.
Each element of the return value is formatted using information from the current
culture. For more information about culture-specific formatting information for the
current culture, see CultureInfo.CurrentCulture.
For For more information about the standard formatting specifiers
http://msdn2.microsoft.com/en-
us/library/system.globalization.datetimeformatinfo.aspx
Converts the value of this instance to all the string representations supported by the
specified standard DateTime format specifier.
Parameter Description
format A Standard DateTime format string or a Custom DateTime Format String
A string array where each element is the representation of the value of this instance
formatted with the format standard DateTime formatting specifier.
Each element of the return value is formatted using information from the current
culture. For more information about culture-specific formatting information for the
current culture, see CultureInfo.CurrentCulture.
For For more information about the standard formatting specifiers
http://msdn2.microsoft.com/en-
us/library/system.globalization.datetimeformatinfo.aspx
Converts the value of this instance to all the string representations supported by the
standard DateTime format specifiers and the specified culture-specific formatting
information.
Parameter Description
An IFormatProvider that supplies culture-specific formatting
provider
information about this instance.
A string array where each element is the representation of the value of this instance
formatted with one of the standard DateTime formatting specifiers.
Converts the value of this instance to all the string representations supported by the
standard DateTime format specifiers and the specified culture-specific formatting
information.
Parameter Description
format A Standard DateTime format string or a Custom DateTime Format String
An IFormatProvider that supplies culture-specific formatting
provider
information about this instance.
A string array where each element is the representation of the value of this instance
formatted with one of the standard DateTime formatting specifiers.
http://msdn2.microsoft.com/en-
us/library/system.globalization.datetimeformatinfo.aspx
DateTime.GetHashCode () Method
returnValue = instance.GetHashCode()
DateTime.GetTypeCode () Method
instance.GetTypeCode()
DateTime.IsDaylightSavingTime () Method
Indicates whether this instance of DateTime is within the Daylight Saving Time range
for the current time zone.
instance.IsDaylightSavingTime ()
true if Kind is Local or Unspecified and the value of this instance of DateTime is
within the Daylight Saving Time range for the current time zone. false if Kind is Utc.
instance.IsLeapYear( year )
Parameter Description
year A 4-digit year.
Adds a specified time interval to a specified date and time, yielding a new date and time.
instance.op_Addition( d, t )
Parameter Description
d A DateTime object
t A TimeSpan object
instance.op_Equality( d1, d2 )
Parameter Description
d1 A DateTime object
d2 A DateTime object
true if d1 and d2 represent the same date and time; otherwise, false.
instance.op_GreaterThan( t1, t2 )
Parameter Description
t1 A DateTime object
t2 A DateTime object
instance.op_GreaterThanOrEqual( t1, t2 )
Parameter Description
t1 A DateTime object
t2 A DateTime object
instance.op_Equality( d1, d2 )
Parameter Description
d1 A DateTime object
d2 A DateTime object
true if d1 and d2 do not represent the same date and time; otherwise, false.
Determines whether one specified DateTime is less than another specified DateTime
instance.op_LessThan( t1, t2 )
Parameter Description
t1 A DateTime object
t2 A DateTime object
Determines whether one specified DateTime is less than or equal to another specified
DateTime
instance.op_LessThanOrEqual( t1, t2 )
Parameter Description
t1 A DateTime object
t2 A DateTime object
DateTime.op_Subtraction Method
Name Description
DateTime.op_Subtraction Subtracts a specified date and time from another
(DateTime, DateTime) specified date and time, yielding a time interval.
DateTime.op_Subtraction Subtracts a specified time interval from a specified
(DateTime, TimeSpan) date and time, yielding a new date and time.
Subtracts a specified date and time from another specified date and time,
yielding a time interval.
instance.op_Subtract( d1, d2 )
Parameter Description
d1 A DateTime (the minuend).
d2 A DateTime (the subtrahend).
A TimeSpan that is the time interval between d1 and d2; that is, d1 minus d2.
Subtracts a specified time interval from a specified date and time, yielding a new date
and time.
instance.op_Subtract( d, t )
Parameter Description
d A DateTime.
t A TimeSpan.
This method subtracts the ticks value of t from the ticks value of d.
DateTime.Parse Method
Name Description
Converts the specified string representation of a date
DateTime.Parse (String)
and time to its DateTime equivalent.
Converts the specified string representation of a date
DateTime.Parse (String,
and time to its DateTime equivalent using the
IFormatProvider)
specified culture-specific format information.
DateTime.Parse (String, Converts the specified string representation of a date
Converts the specified string representation of a date and time to its DateTime
equivalent.
instance.Parse( s )
Parameter Description
s string containing a date and time to convert.
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified culture-specific format information.
instance.Parse( s, provider )
Parameter Description
s string containing a date and time to convert.
An IFormatProvider that supplies culture-specific format information
provider
about s.
method, in contrast, requires you to explicitly designate one or more exact parse
patterns that are likely to succeed.
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified culture-specific format information and formatting style.
Parameter Description
s string containing a date and time to convert.
An IFormatProvider that supplies culture-specific format information
provider
about s.
A bitwise combination of DateTimeStyles values that indicates the
styles
permitted format of s. A typical value to specify is None.
DateTime.ParseExact Method
Name Description
DateTime.ParseExact (String, Converts the specified string representation of a date
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified format and culture-specific format information. The format
of the string representation must match the specified format exactly.
Parameter Description
s A string containing a date and time to convert.
format The expected format of s.
An IFormatProvider that supplies culture-specific format information
provider
about s.
The s parameter contains the date and time to parse. If the s parameter contains
only a time and no date, the current date is used. If the s parameter contains only a
date and no time, midnight (00:00:00) is used. The s parameter cannot contain
leading, inner, or trailing white space characters.
The format parameter contains a pattern that corresponds to the expected format of
the s parameter. The pattern in the format parameter consists of one or more
custom format specifiers from the Custom DateTime Format Strings table, or a
single standard format specifier, which identifies a predefined pattern, from the
Standard DateTime Format Strings table.
If you do not use date or time separators in a custom format pattern, use the
invariant culture for the provider parameter and the widest form of each custom
format specifier. For example, if you want to specify hours in the pattern, specify the
wider form, "HH", instead of the narrower form, "H".
The provider parameter supplies culture-specific date and time formatting
information, such as the names of the days of the week in a particular language, or
the preferred presentation order of the month, day, and year. The format parameter
is typically a culture represented by a CultureInfo object. If provider is a null
reference (Nothing in Visual Basic), the current culture is used.
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified format, culture-specific format information, and style. The
format of the string representation must match the specified format exactly
Parameter Description
s A string containing a date and time to convert.
format The expected format of s.
provider An IFormatProvider that supplies culture-specific format information
about s.
A bitwise combination of DateTimeStyles values that indicates the
styles
permitted format of s. A typical value to specify is None.
The s parameter contains the date and time to parse. If the s parameter contains
only a time and no date, the current date is used. If the s parameter contains only a
date and no time, midnight (00:00:00) is used. The s parameter cannot contain
leading, inner, or trailing white space characters.
The format parameter contains a pattern that corresponds to the expected format of
the s parameter. The pattern in the format parameter consists of one or more
custom format specifiers from the Custom DateTime Format Strings table, or a
single standard format specifier, which identifies a predefined pattern, from the
Standard DateTime Format Strings table.
If you do not use date or time separators in a custom format pattern, use the
invariant culture for the provider parameter and the widest form of each custom
format specifier. For example, if you want to specify hours in the pattern, specify the
wider form, "HH", instead of the narrower form, "H".
The provider parameter supplies culture-specific date and time formatting
information, such as the names of the days of the week in a particular language, or
the preferred presentation order of the month, day, and year. The format parameter
is typically a culture represented by a CultureInfo object. If provider is a null
reference (Nothing in Visual Basic), the current culture is used.
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified format, culture-specific format information, and style. The
format of the string representation must match the specified format exactly
Parameter Description
s A string containing a date and time to convert.
The s parameter contains the date and time to parse. If the s parameter contains
only a time and no date, the current date is used. If the s parameter contains only a
date and no time, midnight (00:00:00) is used. The s parameter cannot contain
leading, inner, or trailing white space characters.
The format parameter contains a pattern that corresponds to the expected format of
the s parameter. The pattern in the format parameter consists of one or more
custom format specifiers from the Custom DateTime Format Strings table, or a
single standard format specifier, which identifies a predefined pattern, from the
Standard DateTime Format Strings table.
If you do not use date or time separators in a custom format pattern, use the
invariant culture for the provider parameter and the widest form of each custom
format specifier. For example, if you want to specify hours in the pattern, specify the
wider form, "HH", instead of the narrower form, "H".
The provider parameter supplies culture-specific date and time formatting
information, such as the names of the days of the week in a particular language, or
the preferred presentation order of the month, day, and year. The format parameter
is typically a culture represented by a CultureInfo object. If provider is a null
reference (Nothing in Visual Basic), the current culture is used.
Creates a new DateTime object that represents the same time as the specified
DateTime, but is designated in either local time, Coordinated Universal Time (UTC), or
neither, as indicated by the specified DateTimeKind value.
Parameter Description
value A DateTime object.
kind One of the DateTimeKind values.
A new DateTime object consisting of the same time represented by the value
parameter and the DateTimeKind value specified by the kind parameter.
A DateTime object consists of a Kind field that indicates whether the time value is
based on local time, Coordinated Universal Time (UTC), or neither, and a Ticks field
that contains a time value measured in 100-nanosecond ticks. The SpecifyKind
method creates a new DateTime object using the specified kind parameter and the
original time value.
The SpecifyKind method is useful in interoperability scenarios where you receive a
DateTime object with an unspecified Kind field, but you can determine by
independent means that the Ticks field represents local time or UTC.
DateTime.Subtract Method
Name Description
Subtracts the specified date and time from this
DateTime.Subtract (DateTime)
instance.
DateTime.Subtract (TimeSpan) Subtracts the specified duration from this instance.
Adds a specified time interval to a specified date and time, yielding a new date and time.
Parameter Description
value An instance of DateTime.
A TimeSpan interval equal to the date and time represented by this instance minus
the date and time represented by value
This method does not change the value of this DateTime object. Instead, a new
TimeSpan is returned whose value is the result of this operation.
Before subtracting DateTime objects, insure that the objects represent times in the
same time zone. Otherwise, the result will include the difference between time
zones.
Parameter Description
value An instance of TimeSpan.
A DateTime equal to the date and time represented by this instance minus the time
interval represented by value.
This method does not change the value of this DateTime. Instead, a new DateTime
is returned whose value is the result of this operation
DateTime.ToFileTime () Method
Converts the value of the current DateTime object to a Windows file time.
instance.ToFileTime()
The value of the current DateTime object expressed as a Windows file time.
A Windows file time is a 64-bit value that represents the number of 100-nanosecond
intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.)
Coordinated Universal Time (UTC). Windows uses a file time to record when an
application creates, accesses, or writes to a file.
Previous versions of the ToFileTime method assume the current DateTime object
is a local time. Starting with the.NET Framework version 2.0, the ToFileTime
method uses the Kind property to determine whether the current DateTime object
is a local time, a UTC time, or an unspecified kind of time which is treated as a local
time.
DateTime.ToFileTimeUtc () Method
Converts the value of the current DateTime object to a Windows file time.
The value of the current DateTime object expressed as a Windows file time.
A Windows file time is a 64-bit value that represents the number of 100-nanosecond
intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.)
Coordinated Universal Time (UTC). Windows uses a file time to record when an
application creates, accesses, or writes to a file.
Prior versions of the ToFileTimeUtc method assume the current DateTime object
is a UTC time. Starting with the.NET Framework version 2.0, the ToFileTimeUtc
method uses the Kind property to determine whether the current DateTime object
is a local time, a UTC time, or an unspecified kind of time which is treated as a UTC
time.
DateTime.ToLocalTime () Method
A DateTime object whose Kind property is Local, and whose value is the local time
equivalent to the value of the current DateTime object, or MaxValue if the converted
value is too large to be represented by a DateTime object, or MinValue if the
converted value is too small to be represented as a DateTime object.
The local time is equal to the UTC time plus the UTC offset. For more information
about the UTC offset, see TimeZone.GetUtcOffset. The conversion also takes into
account the daylight saving time rule that applies to the time represented by the
current DateTime object.
DateTime.ToLongDateString () Method
Converts the value of the current DateTime object to its equivalent long date
returnValue = instance.ToLongDateString()
A string that contains the long date string representation of the current DateTime
object.
The value of the current DateTime object is formatted using the long date format
character, 'D'. The long date format character represents the pattern defined by the
LongDatePattern property associated with the current thread culture. The return
value is identical to the value returned by specifying the "D" standard DateTime
format string with the ToString(String) method.
For more information about the current thread culture, see the CurrentCulture
property. For more information about format characters, format patterns, and the
output they produce, see the Formatting Overview topic. For more information about
changing the format pattern associated with a format character, see the
DateTimeFormatInfo class.
msg1 = _
"The date and time patterns are defined in the DateTimeFormatInfo " & vbCrLf & _
"object associated with the current appliation culture." & vbCrLf
DateTime.ToLongTimeString () Method
Converts the value of the current DateTime object to its equivalent long time string
representation.
returnValue = instance.ToLongTimeString()
A string that contains the long time string representation of the current DateTime
object.
The value of the current DateTime object is formatted using the long date format
character, 'D'. The long date format character represents the pattern defined by the
LongDatePattern property associated with the current thread culture. The return
value is identical to the value returned by specifying the "D" standard DateTime
format string with the ToString(String) method.
For more information about the current thread culture, see the CurrentCulture
property. For more information about format characters, format patterns, and the
output they produce, see the Formatting Overview topic. For more information about
changing the format pattern associated with a format character, see the
DateTimeFormatInfo class.
DateTime.ToShortDateString () Method
Converts the value of the current DateTime object to its equivalent short date string
representation.
returnValue = instance.ToShortDateString()
A string that contains the short date string representation of the current DateTime
object.
The value of the current DateTime object is formatted using the long date format
character, 'D'. The long date format character represents the pattern defined by the
LongDatePattern property associated with the current thread culture. The return
value is identical to the value returned by specifying the "D" standard DateTime
format string with the ToString(String) method.
For more information about the current thread culture, see the CurrentCulture
property. For more information about format characters, format patterns, and the
output they produce, see the Formatting Overview topic. For more information about
changing the format pattern associated with a format character, see the
DateTimeFormatInfo class.
DateTime.ToShortTimeString () Method
Converts the value of the current DateTime object to its equivalent short time string
representation.
returnValue = instance.ToShortTimeString()
A string that contains the long time string representation of the current DateTime
object.
The value of the current DateTime object is formatted using the long date format
character, 'D'. The long date format character represents the pattern defined by the
LongDatePattern property associated with the current thread culture. The return
value is identical to the value returned by specifying the "D" standard DateTime
format string with the ToString(String) method.
For more information about the current thread culture, see the CurrentCulture
property. For more information about format characters, format patterns, and the
output they produce, see the Formatting Overview topic. For more information about
changing the format pattern associated with a format character, see the
DateTimeFormatInfo class.
DateTime.ToString Method
Name Description
Converts the value of the current DateTime object to
DateTime.ToString ()
its equivalent string representation.
Converts the value of the current DateTime object to
DateTime.ToString
its equivalent string representation using the specified
(IFormatProvider)
culture-specific format information.
Converts the value of the current DateTime object to
DateTime.ToString (String) its equivalent string representation using the specified
format.
Converts the value of the current DateTime object to
DateTime.ToString (String,
its equivalent string representation using the specified
IFormatProvider)
format and culture-specific format information.
DateTime.ToString () Method
Converts the value of the current DateTime object to its equivalent string
representation.
returnValue = instance.ToString()
The value of the current DateTime object is formatted using the general date and
time format specifier ('G').
The .NET Framework provides extensive formatting support, which is described in
greater detail in the following formatting topics:
For more information about date and time format specifiers, see Standard
DateTime Format Strings and Custom DateTime Format Strings.
For more information about formatting, see Formatting Types and Formatting
Overview.
This method uses formatting information derived from the current culture. For more
information, see CurrentCulture.
' ** Display the thread current culture, which is used to format the values.
Set ci = DotNetFactory.CreateInstance( _
"System.Windows.Forms.Application" ).CurrentCulture()
Print "Culture --> " & ci.DisplayName
Print msg( "MSG_SHORT_DATE" ) & thisDate.ToString( "d" )
Print msg( "MSG_LONG_DATE" ) & thisDate.ToString( "D" )
Print msg( "MSG_SHORT_TIME" ) & thisDate.ToString( "t" )
Print msg( "MSG_LONG_TIME" ) & thisDate.ToString( "T" )
Print msg( "MSG_FULLSHORT_TIME" ) & thisDate.ToString( "f" )
Print msg( "MSG_FULLLONG_TIME" ) & thisDate.ToString( "F" )
Print msg( "MSG_GENSHORT_TIME" ) & thisDate.ToString( "g" )
Print msg( "MSG_GENLONG_TIME" ) & thisDate.ToString( "G" )
Print msg( "MSG_MONTH" ) & thisDate.ToString( "M" )
Print msg( "MSG_RFC1123" ) & utcDate.ToString( "R" )
Print msg( "MSG_SORT" ) & thisDate.ToString( "s" )
Print msg( "MSG_UNISOR_VAR" ) & utcDate.ToString( "u" )
Print msg( "MSG_UNISORT" ) & thisDate.ToString( "U" )
Print msg( "MSG_YEAR" ) & thisDate.ToString( "Y" )
Print msg( "MSG_ROUNDTRIP_LOC" ) & thisDate.ToString( "o" )
Print msg( "MSG_ROUNDTRIP_UTC" ) & utcDate.ToString( "o" )
Print msg( "MSG_ROUNDTRIP_UNS" ) & unspecifiedDate.ToString( "o" )
Print String( 50, "=" ) & vbCrLf
' ** Display the same values using a CultureInfo object. The CultureInfo class
' ** implements IFormatProvider.
Converts the value of the current DateTime object to its equivalent string
representation using the specified culture-specific format information.
Parameter Description
provider An IFormatProvider that supplies culture-specific formatting information.
The value of the current DateTime object is formatted using the general date and
time format specifier ('G').
The .NET Framework provides extensive formatting support, which is described in
greater detail in the following formatting topics:
For more information about date and time format specifiers, see Standard
DateTime Format Strings and Custom DateTime Format Strings.
For more information about formatting, see Formatting Types and Formatting
Overview.
This method uses formatting information derived from the current culture. For more
information, see CurrentCulture.
Converts the value of the current DateTime object to its equivalent string
representation using the specified format.
Parameter Description
format A DateTime format string.
FormatException
The length of format is 1, and it is not one of the format specifier characters
defined for DateTimeFormatInfo.
format does not contain a valid custom format pattern.
The format parameter should contain either a format specifier character or a custom
format pattern. For more information, see the summary page for
System.Globalization.DateTimeFormatInfo.
If format is a null reference (Nothing in Visual Basic) or an empty string, the general
format specifier, 'G', is used.
The .NET Framework provides extensive formatting support, which is described in
greater detail in the following formatting topics:
For more information about date and time format specifiers, see Standard
DateTime Format Strings and Custom DateTime Format Strings.
For more information about formatting, see Formatting Types and Formatting
Overview.
Converts the value of the current DateTime object to its equivalent string
representation using the specified format and culture-specific format information.
Parameter Description
format A DateTime format string.
provider An IFormatProvider that supplies culture-specific formatting information.
The format parameter should contain either a format specifier character or a custom
format pattern. For more information, see the summary page for
System.Globalization.DateTimeFormatInfo.
If format is a null reference (Nothing in Visual Basic) or an empty string, the general
format specifier, 'G', is used.
The .NET Framework provides extensive formatting support, which is described in
greater detail in the following formatting topics:
For more information about date and time format specifiers, see Standard
DateTime Format Strings and Custom DateTime Format Strings.
For more information about formatting, see Formatting Types and Formatting
Overview.
DateTime.ToUniversalTime () Method
Converts the value of the current DateTime object to Coordinated Universal Time
(UTC).
returnValue = instance.ToUniversalTime()
A DateTime object whose Kind property is Utc, and whose value is the UTC
equivalent to the value of the current DateTime object, or MaxValue if the converted
value is too large to be represented by a DateTime object, or MinValue if the
converted value is too small to be represented by a DateTime object.
The UTC time is equal to the local time minus the UTC offset. For more information
about the UTC offset, see TimeZone.GetUtcOffset. The conversion also takes into
account the daylight saving time rule that applies to the time represented by the
current DateTime object.
The value returned by this conversion is a DateTime object whose Kind property is
Utc. Consequently, a valid result is returned even if ToUniversalTime is applied
repeatedly to the same DateTime object.
This method always uses the local time zone when making calculations.
DateTime.TryParse Method
Name Description
DateTime.TryParse (String, Converts the specified string representation of a date
DateTime) and time to its DateTime equivalent.
Converts the specified string representation of a date
DateTime.TryParse (String,
and time to its DateTime equivalent using the
IFormatProvider, DateTimeStyles,
specified culture-specific format information and
DateTime)
formatting style.
Converts the specified string representation of a date and time to its DateTime
equivalent.
Parameter Description
s A string containing a date and time to convert.
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue if the conversion failed. The conversion fails if the s parameter
result
is a null reference (Nothing in Visual Basic), or does not contain a valid
string representation of a date and time. This parameter is passed
uninitialized.
The TryParse method is similar to the Parse method, except that the TryParse
method does not throw an exception if the conversion fails.
The string s is parsed using formatting information in the current
DateTimeFormatInfo object, which is supplied implicitly by the current thread
culture.
This method attempts to ignore unrecognized data and parse s completely. It
ignores unrecognized data if possible and fills in missing month, day, and year
information with the current time. If s contains only a date and no time, this method
assumes the time is 12:00 midnight. Any leading, inner, or trailing white space
character in s is ignored. The date and time can be bracketed with a pair of leading
and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or
more NULL characters (U+0000).
The s parameter must contain the representation of a date and time in one of the
formats described in the DateTimeFormatInfo class.
Notes to Callers: Formatting is influenced by properties of the current
DateTimeFormatInfo object, which by default are derived from the Regional and
Language Options item in Control Panel. One reason the TryParse method can
unexpectedly throw FormatException is if the current
DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator
properties are set to the same value.
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified culture-specific format information and formatting style.
Parameter Description
s A string containing a date and time to convert.
An IFormatProvider object that supplies culture-specific formatting
result
information about s.
A bitwise combination of DateTimeStyles values that indicates the
styles
permitted format of s. A typical value to specify is None.
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue if the conversion failed. The conversion fails if the s parameter
result
is a null reference (Nothing in Visual Basic), or does not contain a valid
string representation of a date and time. This parameter is passed
uninitialized.
ArgumentException
If format is a null reference (Nothing in Visual Basic) or an empty string, the general
format specifier, 'G', is used.
The .NET Framework provides extensive formatting support, which is described in
greater detail in the following formatting topics:
styles is not a valid DateTimeStyles value.
styles contains an invalid combination of DateTimeStyles values
(for example, both AssumeLocal and AssumeUniversal ).
The TryParse method is similar to the Parse method, except that the TryParse
method does not throw an exception if the conversion fails.
The string s is parsed using formatting information in the current
DateTimeFormatInfo object, which is supplied implicitly by the current thread
culture.
This method attempts to ignore unrecognized data and parse s completely. It
ignores unrecognized data if possible and fills in missing month, day, and year
information with the current time. If s contains only a date and no time, this method
assumes the time is 12:00 midnight. Any leading, inner, or trailing white space
character in s is ignored. The date and time can be bracketed with a pair of leading
and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or
more NULL characters (U+0000).
The s parameter must contain the representation of a date and time in one of the
formats described in the DateTimeFormatInfo class.
The provider parameter supplies culture-specific date and time formatting
information. For example, it might supply the names of the days of the week in a
particular language, or the preferred order of presentation for the month, day, and
year. If provider is a null reference (Nothing in Visual Basic), the current culture is
used.
Notes to Callers: Formatting is influenced by properties of the current
DateTimeFormatInfo object, which by default are derived from the Regional and
Language Options item in Control Panel. One reason the TryParse method can
unexpectedly throw FormatException is if the current
DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator
properties are set to the same value.
DateTime.TryParseExact Method
Name Description
Converts the specified string representation of a date
DateTime.TryParseExact Method and time to its DateTime equivalent using the specified
(String, String, IFormatProvider, format, culture-specific format information, and style.
DateTimeStyles, DateTime) The format of the string representation must match
the specified format exactly.
Converts the specified string representation of a date
DateTime.TryParseExact (String, and time to its DateTime equivalent using the specified
String[], IFormatProvider, array of formats, culture-specific format information,
DateTimeStyles, DateTime) and style. The format of the string representation must
match at least one of the specified formats exactly
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified format, culture-specific format information, and style. The
format of the string representation must match the specified format exactly.
Parameter Description
s A string containing a date and time to convert.
format The expected format of s.
An IFormatProvider object that supplies culture-specific formatting
provider
information about s.
bitwise combination of one or more DateTimeStyles values that indicate
style
the permitted format of s.
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue if the conversion failed. The conversion fails if the s parameter
result
is a null reference (Nothing in Visual Basic), or does not contain a valid
string representation of a date and time. This parameter is passed
uninitialized.
ArgumentException
styles is not a valid DateTimeStyles value.
styles contains an invalid combination of DateTimeStyles values
(for example, both AssumeLocal and AssumeUniversal ).
The TryParseExact method is similar to the ParseExact method, except that the
TryParseExact method does not throw an exception if the conversion fails.
The s parameter contains the date and time to parse. If the s parameter contains
only a time and no date, the style parameter determines whether the current date
or a default date is used. If the s parameter contains only a date and no time,
midnight (00:00:00) is used. The style parameter also determines whether the s
parameter can contain leading, inner, or trailing white space characters
The format parameter contains a pattern that corresponds to the expected format
of the s parameter. The pattern in the format parameter consists of one or more
custom format specifiers from the Custom DateTime Format Strings table, or a
single standard format specifier, which identifies a predefined pattern, from the
Standard DateTime Format Strings table.
If you do not use date or time separators in a custom format pattern, use the
invariant culture for the provider parameter and the widest form of each custom
format specifier. For example, if you want to specify hours in the pattern, specify the
wider form, "HH", instead of the narrower form, "H".
The provider parameter supplies culture-specific date and time formatting
information, such as the names of the days of the week in a particular language, or
the preferred presentation order of the month, day, and year. The format
parameter is typically a culture represented by a CultureInfo object. If provider is a
null reference (Nothing in Visual Basic), the current culture is used.
Converts the specified string representation of a date and time to its DateTime
equivalent using the specified format, culture-specific format information, and style. The
format of the string representation must match the specified format exactly.
Parameter Description
s A string containing a date and time to convert.
formats An array of expected formats of s.
An IFormatProvider object that supplies culture-specific formatting
provider
information about s.
bitwise combination of one or more DateTimeStyles values that indicate
style
the permitted format of s.
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue if the conversion failed. The conversion fails if the s parameter
result
is a null reference (Nothing in Visual Basic), or does not contain a valid
string representation of a date and time. This parameter is passed
uninitialized.
ArgumentException
styles is not a valid DateTimeStyles value.
styles contains an invalid combination of DateTimeStyles values
(for example, both AssumeLocal and AssumeUniversal ).
The TryParseExact method is similar to the ParseExact method, except that the
TryParseExact method does not throw an exception if the conversion fails.
The s parameter contains the date and time to parse. If the s parameter contains
only a time and no date, the style parameter determines whether the current date
or a default date is used. If the s parameter contains only a date and no time,
midnight (00:00:00) is used. The style parameter also determines whether the s
parameter can contain leading, inner, or trailing white space characters
The format parameter contains a pattern that corresponds to the expected format
of the s parameter. The pattern in the format parameter consists of one or more
custom format specifiers from the Custom DateTime Format Strings table, or a
single standard format specifier, which identifies a predefined pattern, from the
Standard DateTime Format Strings table.
If you do not use date or time separators in a custom format pattern, use the
invariant culture for the provider parameter and the widest form of each custom
format specifier. For example, if you want to specify hours in the pattern, specify the
wider form, "HH", instead of the narrower form, "H".
The provider parameter supplies culture-specific date and time formatting
information, such as the names of the days of the week in a particular language, or
the preferred presentation order of the month, day, and year. The format
System.TimeSpan Structure
System.TimeSpan Contructors
Name Description
Initializes a new TimeSpan to the specified number
TimeSpan (Int64)
of ticks.
Initializes a new TimeSpan to a specified number of
TimeSpan (Int32, Int32, Int32)
hours, minutes, and seconds.
TimeSpan (Int32, Int32, Int32, Initializes a new TimeSpan to a specified number of
Int32) days, hours, minutes, and seconds.
TimeSpan (Int32, Int32, Int32, Initializes a new TimeSpan to a specified number of
Int32, Int32) days, hours, minutes, seconds, and milliseconds.
Set object =
DotNetFactory.CreateInstance( "System.TimeSpan", , ticks )
Parameter Description
System.TimeSpan object
The following code example creates several TimeSpan objects using the constructor
overload that initializes a TimeSpan to a specified number of ticks.
Option Explicit
Dim int64
Set object =
DotNetFactory.CreateInstance( "System.TimeSpan", , hours, minutes,
seconds )
Parameter Description
hours Number of hours.
minutes Number of minutes.
seconds Number of seconds.
System.TimeSpan object
The specified hours, minutes, and seconds are converted to ticks, and that value
initializes this instance.
The following code example creates several TimeSpan objects using the constructor
overload that initializes a TimeSpan to a specified number of hours, minutes, and
seconds.
Option Explicit
' ** Create a TimeSpan object and display its value.
Sub CreateTimeSpan( ByVal hours, ByVal minutes, ByVal seconds )
Dim ctor, sb
Dim elapsedTime
Print "This example of the TimeSpan( Integer, Integer, Integer ) constructor " & _
vbCrLf & "generates the following output." & vbCrLf
Call CreateTimeSpan( 10, 20, 30 )
Call CreateTimeSpan( -10, 20, 30 )
Call CreateTimeSpan( 0, 0, 37230 )
Call CreateTimeSpan( 1000, 2000, 3000 )
Call CreateTimeSpan( 1000, -2000, -3000 )
Call CreateTimeSpan( 999999, 999999, 999999 )
Initializes a new TimeSpan to a specified number of days, hours, minutes, and seconds.
Set object =
DotNetFactory.CreateInstance( "System.TimeSpan", , days, hours, minutes,
seconds )
Parameter Description
days Number of days.
hours Number of hours.
minutes Number of minutes.
seconds Number of seconds.
System.TimeSpan object
The specified days, hours, minutes, and seconds are converted to ticks, and that
value initializes this instance.
The following code example creates several TimeSpan objects using the constructor
overload that initializes a TimeSpan to a specified number of days, hours, minutes,
and seconds.
Option Explicit
' ** Create a TimeSpan object and display its value.
Sub CreateTimeSpan( ByVal Days, ByVal hours, ByVal minutes, ByVal seconds )
Dim ctor, sb
Dim elapsedTime
Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and
milliseconds.
Set object =
DotNetFactory.CreateInstance( "System.TimeSpan", , days, hours, minutes,
seconds, milliseconds )
Parameter Description
days Number of days.
hours Number of hours.
minutes Number of minutes.
seconds Number of seconds.
milliseconds Number of milliseconds
System.TimeSpan object
The specified days, hours, minutes, seconds, and milliseconds are converted to
ticks, and that value initializes this instance.
The following code example creates several TimeSpan objects using the constructor
overload that initializes a TimeSpan to a specified number of days, hours, minutes,
seconds, and milliseconds.
Option Explicit
' ** Create a TimeSpan object and display its value.
Sub CreateTimeSpan( _
ByVal Days, ByVal hours, ByVal minutes, ByVal seconds, ByVal milliseconds )
Dim ctor, sb
Dim elapsedTime
System.TimeSpan Fields
Name Description
MaxValue Represents the maximum TimeSpan value. This field is read-only.
MinValue Represents the minimum TimeSpan value. This field is read-only.
TicksPerDay Represents the number of ticks in 1 day. This field is constant.
TicksPerHour Represents the number of ticks in 1 hour. This field is constant.
TicksPerMillisecond Represents the number of ticks in 1 millisecond. This field is constant.
TicksPerMinute Represents the number of ticks in 1 minute. This field is constant.
TicksPerSecond Represents the number of ticks in 1 second.
Zero Represents the zero TimeSpan value. This field is read-only
TimeSpan.MaxValue Field
The following code example references and displays the value of the MaxValue field.
Option Explicit
Dim timeSpan
TimeSpan.MinValue Field
The value of this field is equivalent to Int64.MinValue ticks. The string representation
of this value is negative 10675199.02:48:05.4775808.
TimeSpan.TicksPerDay Field
TimeSpan.TicksPerHour Field
TimeSpan.TicksPerMillisecond Field
TimeSpan.TicksPerMinute Field
TimeSpan.TicksPerSecond Field
TimeSpan.Zero Field
TimeSpan Properties
Name Description
Gets the number of whole days represented by the current TimeSpan
Days
structure.
Gets the number of whole hours represented by the current TimeSpan
Hours
structure.
Gets the number of whole milliseconds represented by the current
Milliseconds
TimeSpan structure.
Gets the number of whole seconds represented by the current
Minutes
TimeSpan structure.
Gets the number of whole seconds represented by the current
Seconds
TimeSpan structure.
Gets the number of ticks that represent the value of the current
Ticks
TimeSpan structure.
TimeSpan.Days Property
Gets the number of whole days represented by the current TimeSpan structure.
returnValue = object.Days
The day component of this instance. The return value can be positive or negative.
The following code example creates several TimeSpan objects and displays the Days
property of each.
Option Explicit
End Sub
TimeSpan.Hours Property
Gets the number of whole days represented by the current TimeSpan structure.
returnValue = object.Hours
The day component of this instance. The return value can be positive or negative.
The following code example creates several TimeSpan objects and displays the Hours
property of each. See Example TimeSpan Properties
TimeSpan.Milliseconds Property
Gets the number of whole milliseconds represented by the current TimeSpan structure.
returnValue = object.Milliseconds
The millisecond component of the current TimeSpan structure. The return value ranges
from -999 through 999.
The following code example creates several TimeSpan objects and displays the
Milliseconds property of each. See Example TimeSpan Properties
TimeSpan.Minutes Property
Gets the number of whole minutes represented by the current TimeSpan structure.
returnValue = object.Minutes
The minute component of the current TimeSpan structure. The return value ranges from
-59 through 59.
minus sign indicates a negative time interval, the d component is days, hh is hours
as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of
a second. The value of the Minutes property is the minute component, mm.
The following code example creates several TimeSpan objects and displays the
Minutes property of each. See Example TimeSpan Properties
TimeSpan.Seconds Property
Gets the number of whole seconds represented by the current TimeSpan structure.
returnValue = object.Seconds
The second component of the current TimeSpan structure. The return value ranges from
-59 through 59.
The following code example creates several TimeSpan objects and displays the
Seconds property of each. See Example TimeSpan Properties
TimeSpan.Ticks Property
Gets the number of ticks that represent the value of the current TimeSpan structure.
returnValue = object.Ticks
The smallest unit of time is the tick, which is equal to 100 nanoseconds. A tick can
be negative or positive.
The following code example creates several TimeSpan objects and displays the Ticks
property of each. See Example TimeSpan Properties
TimeSpan.TotalDays Property
Gets the value of the current TimeSpan structure expressed in whole and fractional
days.
returnValue = object.TotalDays
This property converts the value of this instance from ticks to days. This number
might include whole and fractional days
The following code example creates several TimeSpan objects and displays the
TotalDays property of each. See Example TimeSpan Properties
TimeSpan.TotalHours Property
Gets the value of the current TimeSpan structure expressed in whole and fractional
hours.
returnValue = object.TotalHours
This property converts the value of this instance from ticks to hours. This number
might include whole and fractional hours.
The following code example creates several TimeSpan objects and displays the
TotalHours property of each. See Example TimeSpan Properties
TimeSpan.TotalMilliseconds Property
Gets the value of the current TimeSpan structure expressed in whole and fractional
milliseconds.
returnValue = object.TotalMilliseconds
This property converts the value of this instance from ticks to milliseconds. This
The following code example creates several TimeSpan objects and displays the
TotalMilliseconds property of each. See Example TimeSpan Properties
TimeSpan.TotalMinutes Property
Gets the value of the current TimeSpan structure expressed in whole and fractional
minutes.
returnValue = object.TotalMinutes
This property converts the value of this instance from ticks to minutes. This number
might include whole and fractional minutes.
The following code example creates several TimeSpan objects and displays the
TotalMinutes property of each. See Example TimeSpan Properties
TimeSpan.TotalSeconds Property
Gets the value of the current TimeSpan structure expressed in whole and fractional
seconds.
returnValue = object.TotalSeconds
This property converts the value of this instance from ticks to seconds. This number
might include whole and fractional seconds..
The following code example creates several TimeSpan objects and displays the
TotalSeconds property of each. See Example TimeSpan Properties
TimeSpan Methods
Name Description
Add Adds the specified TimeSpan to this instance.
Parameter Description
ts A TimeSpan
A TimeSpan that represents the value of this instance plus the value of ts.
The following code example creates several pairs of TimeSpan objects and calculates
their sum with the Add method.
Option Explicit
Compares two TimeSpan values and returns an integer that indicates their relationship.
Parameter Description
t1 The first DateTime.
t2 The second DateTime.
' ** Compare TimeSpan parameters, and display them with the results.
Sub CompareTimeSpans( ByRef tsLeft, ByRef tsRight, ByVal RightText )
Dim sb
Print "Right : " & RightText & " ---> " & tsRight
Print "TimeSpan.Equals( Left, Right ) ---> " & ts.Equals( tsLeft, tsRight )
Print "TimeSpan.Compare( Left, Right ) ---> " & ts.Compare( tsLeft, tsRight )
End Sub
Compares this instance to a specified TimeSpan object and returns an indication of their
relative values.
Parameter Description
value A TimeSpan object to compare to this instance.
TimeSpan.Duration ( ) Method
Returns a new TimeSpan object whose value is the absolute value of the current
TimeSpan object.
Set ts = instance.Duration()
A new TimeSpan whose value is the absolute value of the current TimeSpan
object. Example
The following code example applies the Duration method to several TimeSpan objects.
Option Explicit
' ** Display the TimeSpan value and the results of the Duration and Negate
' methods.
Print "Interval ---> " & interval
Print "Interval.Duration ---> " & interval.Duration
Print "Interval.Negate ---> " & interval.Negate
End Sub
Call ShowDurationNegate( ts )
Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, -10, 20, -30, 40 )
Set unaryTs = DotNetFactory.CreateInstance( "System.TimeSpan" ).op_UnaryPlus( ts )
Call ShowDurationNegate( ts )
Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 10, 20, 40, 160 )
Set unaryTs = DotNetFactory.CreateInstance("System.TimeSpan").op_UnaryNegation( ts )
Call ShowDurationNegate( ts )
Set ts = DotNetFactory.CreateInstance("System.TimeSpan",, -10, -20, -30, -40, -50 )
Set unaryTs = DotNetFactory.CreateInstance("System.TimeSpan").op_UnaryNegation( ts )
Call ShowDurationNegate( ts )
Set ts = Nothing : Set unaryTs = Nothing
TimeSpan.Equals Method
Name Description
Returns a value indicating whether this instance is equal
TimeSpan.Equals (TimeSpan)
to a specified TimeSpan object.
TimeSpan.Equals (TimeSpan, Returns a value indicating whether two specified
TimeSpan) instances of TimeSpan are equal.
Returns a value indicating whether two specified instances of TimeSpan are equal.
Parameter Description
obj A TimeSpan object to compare with this instance.
true if obj represents the same time interval as this instance; otherwise, false.
Returns a value indicating whether two specified instances of TimeSpan are equal
Parameter Description
t1 A TimeSpan
t2 A TimeSpan
Returns a TimeSpan that represents a specified number of days, where the specification
is accurate to the nearest millisecond.
Parameter Description
value A number of days, accurate to the nearest millisecond.
The following code example creates several TimeSpan objects using the FromDays
method.
Option Explicit
Dim ts
Sub GenTimeSpanFromDays( ByRef days )
Dim interval, timeInterval
' ** Create a TimeSpan object and TimeSpan string from a number of days.
Set interval = ts.FromDays( days )
timeInterval = interval.ToString( )
Print "days ---> " & days
Print "time Interval ---> " & timeInterval
Set interval = Nothing
End Sub
Print "This example of TimeSpan.FromDays( Double )" & vbCrLf & _
"generates the following output." & vbCrLf
Parameter Description
value A number of hours accurate to the nearest millisecond.
The following code example creates several TimeSpan objects using the FromHours
method.
Option Explicit
Dim ts
Sub GenTimeSpanFromHours( ByRef hours )
Dim interval, timeInterval
' ** Create a TimeSpan object and TimeSpan string from a number of hours.
Set interval = ts.FromHours( hours )
timeInterval = interval.ToString( )
Print "hours ---> " & hours
Print "time Interval ---> " & timeInterval
Set interval = Nothing
End Sub
Print "This example of TimeSpan.FromHours( Double )" & _
vbCrLf & "generates the following output." & vbCrLf
Parameter Description
value A number of milliseconds.
The following code example creates several TimeSpan objects using the FromHours
method.
Option Explicit
Dim ts
Sub GenTimeSpanFromMillisec( ByRef millisec )
Dim interval, timeInterval
' ** Create a TimeSpan object and TimeSpan string from a number of millisecs.
Set interval = ts.FromMilliseconds( millisec )
timeInterval = interval.ToString( )
Print "milliseconds ---> " & millisec
Print "time Interval ---> " & timeInterval
Set interval = Nothing
End Sub
Print "This example of TimeSpan.FromMilliseconds ( Double )" & _
vbCrLf & "generates the following output." & vbCrLf
Parameter Description
value A number of minutes, accurate to the nearest millisecond.
Parameter Description
value A number of seconds, accurate to the nearest millisecond.
The following code example creates several TimeSpan objects using the FromHours
method.
Option Explicit
Dim ts
Sub GenTimeSpanFromSeconds( ByRef seconds )
Dim interval, timeInterval
' ** Create a TimeSpan object and TimeSpan string from a number of seconds.
Set interval = ts.FromSeconds( seconds )
timeInterval = interval.ToString( )
Print " seconds ---> " & seconds
Print "time Interval ---> " & timeInterval
Set interval = Nothing
End Sub
Print "This example of TimeSpan.FromMinutes ( Double )" & _
vbCrLf & "generates the following output." & vbCrLf
Returns a TimeSpan that represents a specified time, where the specification is in units
of ticks.
Parameter Description
value A number of ticks that represent a time.
This is a convenience method with the same behavior as the TimeSpan constructor.
TimeSpan.GetHashCode ( ) Method
Returns a TimeSpan that represents a specified time, where the specification is in units
of ticks.
returnValue = instance.GetHashCode()
Two TimeSpan objects might have the same hash code even though they represent
different time values.
The following code example generates the hash codes of several TimeSpan objects
using the GetHashCode method.
Option Explicit
Dim ts, int64
' ** Create a hash code and a string representation of the TimeSpan parameter.
timeInterval= interval.ToString( )
hashCode = interval.GetHashCode( )
Print "Interval = " & timeInterval & _
"; hash code = " & Hex( hashCode ) & _
" (" & hashCode & ")"
End Sub
TimeSpan.Negate ( ) Method
returnValue = instance.GetHashCode()
The same numeric value as this instance, but with the opposite sign.
Two TimeSpan objects might have the same hash code even though they represent
different time values.
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
The following code example creates several pairs of TimeSpan objects and calculates
their sum with the Addition operator.
Option Explicit
Dim ts, tsL, tsR, int64L, int64R
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
' ** Compare TimeSpan parameters, and display them with the results.
Sub CompareTimeSpans( ByRef tsLeft, ByRef tsRight, ByVal sText )
Print String( 50, "*" )
Print sText & " ---> Right : " & tsRight.ToString()
Print "TimeSpan.op_Equality( Left, Right ) ---> " & ts.op_Equality( tsLeft, tsRight
)
Print "TimeSpan.op_GreaterThan( Left, Right ) ---> " & ts.op_GreaterThan( tsLeft,
tsRight )
Print "TimeSpan.op_GreaterThanOrEqual( Left, Right ) ---> " &
ts.op_GreaterThanOrEqual( tsLeft, tsRight )
Print "TimeSpan.op_Inequality( Left, Right ) ---> " & ts.op_Inequality( tsLeft,
tsRight )
Print "TimeSpan.op_LessThan( Left, Right ) ---> " & ts.op_LessThan( tsLeft, tsRight
)
Print "TimeSpan.op_LessThanOrEqual( Left, Right ) ---> " & ts.op_LessThanOrEqual(
tsLeft, tsRight )
End Sub
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
true if the value of t1 is greater than the value of t2; otherwise, false.
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
true if the value of t1 is greater than or equal to the value of t2; otherwise, false.
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
true if the value of t1 is less than the value of t2; otherwise, false.
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
true if the value of t1 is less than or equal to the value of t2; otherwise, false.
Parameter Description
t1 A TimeSpan.
t2 A TimeSpan.
A TimeSpan whose value is the result of the value of t1 minus the value of t2.
The following code example creates several pairs of TimeSpan objects and calculates
their difference with the Subtraction operator. See TimeSpan.op_Addition Example
TimeSpan.op_UnaryNegation ( ) Method
Returns a TimeSpan whose value is the negated value of the specified instance.
Set ts = instance.op_UnaryNegation( t )
Parameter Description
t A TimeSpan
A TimeSpan with the same numeric value as this instance, but the opposite sign.
TimeSpan.op_UnaryPlus ( ) Method
Set ts = instance.op_UnaryPlus( t )
Parameter Description
t A TimeSpan
Returns t.
Set ts = instance.Parse( s )
Parameter Description
s A string that specifies a time interval.
OverflowException
s represents a number less than MinValue or greater than MaxValue
At least one of the days, hours, minutes,
or seconds components is outside its valid range.
Item Description
ws optional white space
"-" optional minus sign indicating a negative TimeSpan
d days, ranging from 0 to 10675199
hh hours, ranging from 0 to 23
mm minutes, ranging from 0 to 59
ss optional seconds, ranging from 0 to 59
ff optional fractional seconds, consisting of 1 to 7 decimal digits
The components of s must collectively specify a time interval greater than or equal to
MinValue and less than or equal to MaxValue
The following code example uses the Parse method to create TimeSpan objects from valid
TimeSpan strings and to raise exceptions from invalid TimeSpan strings.
Option Explicit
Dim ts
Parameter Description
ts A TimeSpan
A TimeSpan.
The following code example creates several pairs of TimeSpan objects and calculates
their difference with the Subtract method. See Example TimeSpan Subtract and Add
Methods
returnValue = instance.ToString( )
Item Description
ws optional white space
"-" optional minus sign indicating a negative TimeSpan
d days, ranging from 0 to 10675199
hh hours, ranging from 0 to 23
mm minutes, ranging from 0 to 59
ss optional seconds, ranging from 0 to 59
ff optional fractional seconds, consisting of 1 to 7 decimal digits
For more information about comparing the string representation of TimeSpan and
Oracle data types, see article Q324577, "System.TimeSpan Does Not Match Oracle 9i
INTERVAL DAY TO SECOND Data Type," in the Microsoft Knowledge Base at
http://support.microsoft.com.
Constructs a new TimeSpan object from a time interval specified in a string. Parameters
specify the time interval and the variable where the new TimeSpan object is returned.
Parameter Description
s A string that specifies a time interval.
When this method returns, contains an object that represents the time
result interval specified by s, or Zero if the conversion failed. This parameter is
passed uninitialized.
true if s was converted successfully; otherwise, false. This operation returns false if
the s parameter is a null reference (Nothing in Visual Basic), has an invalid
format,represents a time interval less than MinValue or greater than MaxValue, or has
at least one days, hours, minutes, or seconds component outside its valid range.
The TryParse method is like the TimeSpan.Parse method, except the TryParse method
does not throw an exception if the conversion fails.
The s parameter contains a time interval specification of the form:
[ws][-]{ d | d.hh:mm[:ss[.ff]] | hh:mm[:ss[.ff]] }[ws]
The TryParse method is like the TimeSpan.Parse method, except the TryParse
method does not throw an exception if the conversion fails.
Items in square brackets ([ and ]) are optional. One selection from the list of alternatives
enclosed in braces ({ and }) and separated by vertical bars (|) is required. Colons and
periods (: and .) are literal characters and required. Other items are as follows.
Item Description
ws optional white space
"-" optional minus sign indicating a negative TimeSpan
d days, ranging from 0 to 10675199
hh hours, ranging from 0 to 23
mm minutes, ranging from 0 to 59
ss optional seconds, ranging from 0 to 59
ff optional fractional seconds, consisting of 1 to 7 decimal digits
The components of s must collectively specify a time interval greater than or equal to
MinValue and less than or equal to MaxValue.
DotNetFactory Tasks
World Calendars
The Following code displays the different world calendars using the DOT.NET Calendars
objects, CultutreInfo and more.
Notice to the usage of the dictionary; the dictionary holds a class for every entry.
Option Explicit
Const CULTURE_INFO = "System.Globalization.CultureInfo"
Dim calendarsArr, cultureArr, today
Dim nCal, calName
Dim nDay, nMonth, nYear
Dim calDict
Class CalendarInfo
Private m_calendar, m_culture
Private m_ciName, m_calName
' ** Class private events
Private Sub Class_Initialize()
Set m_calendar = Nothing : Set m_culture = Nothing
End Sub
Private Sub Class_Terminate()
Set m_calendar = Nothing : Set m_culture = Nothing
End Sub
' ** System.Globalization.CultureInfo
Public Property Get CultureInfo()
Set CultureInfo = m_culture
End Property
' ** System.Globalization.Calendar
Public Property Get Calendar()
Set Calendar = m_calendar
End Property
Public Property Let CalendarName( ByVal value )
m_calName = value
Set m_calendar = DotNetFactory.CreateInstance( _
"System.Globalization." & m_calName )
End Property
Public Property Get CalendarName()
CalendarName = m_calName
End Property
Public Property Let CultureName( ByVal value )
m_ciName = value
Set m_culture = DotNetFactory.CreateInstance( _
CULTURE_INFO, "System", m_ciName, True )
Set m_culture.DateTimeFormat.Calendar = m_calendar
End Property
Public Property Get CultureName()
CultureName = m_ciName
End Property
Public Function GetMonthNames( ByVal nYear )
Dim i, outStr
System.Collections.ArrayList
Option Explicit
Dim ArrayList, i, nItem
In WinRunner the feature Call Chain gave the developer the capability to track function
calling in the program flow. Every moment you could see wich function was called by
another function. This can help a lot, when debugging complex scripts. Unfortunately QTP
does not support this great built-in mechanism ( till version 9.2 ). Alternatively you can
build and handle a CallChain of your own using a stack ( the same method is used by the
operating system )
Option Explicit
Dim CallChain ' Can be used as a Global variable
Call Func2()
Call Sub3()
CallChain.Pop
End Function
Private Function Func2()
CallChain.Push( Environment( "ActionName" ) & "::Func2" )
Call Func4()
CallChain.Pop
End Function
Private Sub Sub3()
CallChain.Push( Environment( "ActionName" ) & "::Sub3")
' ** Do Something
CallChain.Pop
End Sub
Private Function Func4()
CallChain.Push( Environment( "ActionName" ) & "::Func4" )
' ** Do Something
CallChain.Pop
End Function
Public Sub ReportCallChain( ByVal saveToFile )
Dim ie, clone, dtStr
How it Works : Put a Breakpoint anywhere inside Func1, Func2, Sub3 or Func4.
When the script gets to the breakpoint, display the Debug Viewer Window, Select the
VisualBasic Functions
Option Explicit
Dim Dim vbi, vbs
Dim response
System.DateTimeKind Enumeration
Constant Value Description
Local 2 The time represented is local time.
Unspecified 0 The time represented is not specified as either local time or Coordinated
Universal Time (UTC).
System.DayOfWeek Enumeration
Constant Val Description
Friday 5 Indicates Friday.
M or m Month Day Represents a custom DateTime format string defined by the current
Pattern DatetimeFormatInfo.MonthDayPattern property.
o Round-trip Represents a custom DateTime format string using a pattern that
date/time preserves time zone information. The pattern is designed to round-trip
pattern DateTime formats, including the Kind property, in text. Then the
formatted string can be parsed back using Parse or ParseExact with
the correct Kind property value.
R or r RFC1123 Represents a custom DateTime format string defined by the current
pattern DatetimeFormatInfo.RFC1123Pattern property. The pattern is a defined
standard and the property is read-only. Therefore, it is always the same
regardless of the culture used or the format provider supplied.
s Sortable Represents a custom DateTime format string defined by the current
date/time DatetimeFormatInfo.SortableDateTimePattern property. This pattern is
pattern; a defined standard and the property is read-only. Therefore, it is always
conforms to the same regardless of the culture used or the format provider
ISO 8601 supplied.
t Short time Represents a custom DateTime format string defined by the current
pattern DatetimeFormatInfo.ShortTimePattern property.
T Long time Represents a custom DateTime format string defined by the current
pattern DatetimeFormatInfo.LongTimePattern property.
u Universal Represents a custom DateTime format string defined by the current
sortable DatetimeFormatInfo.UniversalSortableDateTimePattern property. This
date/time pattern is a defined standard and the property is read-only. Therefore,
pattern it is always the same regardless of the culture used or the format
provider supplied.
U Universal Represents a custom DateTime format string defined by the current
sortable DatetimeFormatInfo.FullDateTimePattern property.
date/time This pattern is the same as the full date/long time (F) pattern.
pattern However, formatting operates on the Coordinated Universal Time (UTC)
that is equivalent to the DateTime object being formatted.
Y or y Year month Represents a custom DateTime format string defined by the current
pattern DatetimeFormatInfo.YearMonthPattern property
Note that if the "f" format specifier is used alone, without other format
specifiers, it is interpreted as the "f" standard DateTime format specifier
(full date/time pattern). For more information about using a single
format specifier, see Using Single Custom Format Specifiers.
When you use this format specifier with the ParseExact or TryParseExact
method, the number of "f" format specifiers that you use indicates the
number of most significant digits of the seconds fraction to parse.
ff Represents the two most significant digits of the seconds fraction.
fff Represents the three most significant digits of the seconds fraction.
ffff Represents the four most significant digits of the seconds fraction.
fffff Represents the five most significant digits of the seconds fraction.
ffffff Represents the six most significant digits of the seconds fraction.
fffffff Represents the seven most significant digits of the seconds fraction.
F Represents the most significant digit of the seconds fraction. Nothing is
displayed if the digit is zero. For more information about using a single
format specifier, see Using Single Custom Format Specifiers.
Note that for the Thai Buddhist calendar, which can have five-digit
years, this format specifier displays all five digits.
yyyy Represents the year as a four-digit number. If the year has more than
four digits, only the four low-order digits appear in the result. If the year
has fewer than four digits, the number is padded with leading zeroes to
achieve four digits.
Note that for the Thai Buddhist calendar, which can have five-digit
years, this format specifier renders all five digits
yyyyy (plus any Represents the year as a five-digit number. If the year has more than
number of additional five digits, only the five low-order digits appear in the result. If the year
"y" specifiers) has fewer than five digits, the number is padded with leading zeroes to
achieve five digits.
If there are additional "y" specifiers, the number is padded with as many
leading zeroes as necessary to achieve the number of "y" specifiers.
z Represents the signed time zone offset of your system from Greenwich
Mean Time (GMT) measured in hours. For example, the offset for a
computer in the Pacific Standard Time zone is "-8".
The offset is always displayed with a leading sign. A plus sign (+)
indicates hours ahead of GMT and a minus sign (-) indicates hours
behind GMT. The offset ranges from –12 through +13. A single-digit
offset is formatted without a leading zero. The offset is affected by
daylight savings time. For more information about using a single format
specifier, see Using Single Custom Format Specifiers.
zz Represents the signed time zone offset of your system from Greenwich
Mean Time (GMT) measured in hours. For example, the offset for a
computer in the Pacific Standard Time zone is "-08".
The offset is always displayed with a leading sign. A plus sign (+)
indicates hours ahead of GMT and a minus sign (-) indicates hours
behind GMT. The offset ranges from –12 through +13. A single-digit
offset is formatted with a leading zero. The offset is affected by daylight
savings time.
zzz, zzz (plus any Represents the signed time zone offset of your system from Greenwich
number of additional Mean Time (GMT) measured in hours and minutes. For example, the
"z" specifiers) offset for a computer in the Pacific Standard Time zone is "-08:00".
The offset is always displayed with a leading sign. A plus sign (+)
indicates hours ahead of GMT and a minus sign (-) indicates hours
behind GMT. The offset ranges from –12 through +13. A single-digit
offset is formatted with a leading zero. The offset is affected by daylight
savings time.
: The time separator defined in the current
System.Globalization.DateTimeFormatInfo.TimeSeparator property that
is used to differentiate hours, minutes, and seconds.
/ The date separator defined in the current
System.Globalization.DateTimeFormatInfo.DateSeparator property that
is used to differentiate years, months, and days.
" Quoted string (quotation mark). Displays the literal value of any string
between two quotation marks ("). Precede each quotation mark with an
escape character (\).
' Quoted string (apostrophe). Displays the literal value of any string
between two apostrophe (') characters.
%c Represents the result associated with a custom format specifier "c",
when the custom DateTime format string consists solely of that custom
format specifier. That is, to use the "d", "f", "F", "h", "m", "s", "t", "y",
"z", "H", or "M" custom format specifier by itself, specify "%d", "%f",
"%F", "%h", "%m", "%s", "%t", "%y", "%z", "%H", or "%M". For more
information about using a single format specifier, see Using Single
Custom Format Specifiers.
\c The escape character. Displays the character "c" as a literal when that
character is preceded by the escape character (\). To insert the
backslash character itself in the result string, use two escape characters
("\\").
Any other character Any other character is copied to the result string, and does not affect
formatting.
System.Globalization.DateTimeStyles Enumeration
Member Value Description
Indicates that the date and time will be returned as a
AdjustToUniversal 16
Coordinated Universal Time (UTC).