Your SlideShare is downloading. ×
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Scripting qtp   ch14 - dot netfactory
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Scripting qtp ch14 - dot netfactory

557

Published on

Published in: Business, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
557
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
18
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Chapter 14 Scripting Quicktest Professional Page 1Dani Vainstein DotNetFactory Page 1 of 151DOTNETFACTORY .................................................................................................................... 4THE DOTNETFACTORY OBJECT................................................................................................ 4CREATEINSTANCE METHOD.................................................................................................. 4QTP DOTNETFACTORY ............................................................................................................. 5SYSTEM.DATETIME STRUCTURE............................................................................................... 9SYSTEM.DATETIME FIELDS................................................................................................... 9DateTime.MaxValue Field............................................................................................ 10DateTime.MinValue Field ............................................................................................ 10SYSTEM.DATETIME CONTRUCTORS.................................................................................... 10DateTime.DateTime( int64 ) Constructor..................................................................... 11DateTime.DateTime ( int64, DateTimeKind ) Constructor .......................................... 12DateTime.DateTime(Int32, Int32, Int32) Constructor.................................................. 14DateTime.DateTime(Int32, Int32, Int32, Calendar) Constructor.................................. 15DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32) Constructor................... 16DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar ) Constructor . 17DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind )Constructor.................................................................................................................... 19DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32 ) Constructor ....... 20DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar )Constructor.................................................................................................................... 20DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind )Constructor.................................................................................................................... 21DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar,DateTimeKind ) Constructor......................................................................................... 22DATETIME PROPERTIES....................................................................................................... 23DateTime.Date Property ............................................................................................... 24DateTime.Day Property ................................................................................................ 25DateTime.DayOfWeek Property................................................................................... 25DateTime.DayOfYear Property .................................................................................... 26DateTime.Hour Property............................................................................................... 27DateTime.Kind Property............................................................................................... 27DateTime.Millisecond Property.................................................................................... 29DateTime.Minute Property ........................................................................................... 29DateTime.Month Property ............................................................................................ 29DateTime.Now Property ............................................................................................... 29DateTime.Second Property ........................................................................................... 30DateTime.Ticks Property .............................................................................................. 30DateTime.TimeOfDay Property.................................................................................... 30DateTime.Today Property............................................................................................. 31DateTime.UtcNow Property ......................................................................................... 31DateTime.Year Property ............................................................................................... 32DATETIME METHODS.......................................................................................................... 32DateTime.Add ( TimeSpan ) Method ........................................................................... 34DateTime.AddDays ( Double ) Method........................................................................ 35DateTime.AddHours ( Double ) Method ...................................................................... 36DateTime.AddMilliseconds ( Double ) Method ........................................................... 36DateTime.AddMinutes ( Double ) Method................................................................... 37DateTime.AddMonths ( Integer ) Method .................................................................... 37
  • 2. Chapter 14 Scripting Quicktest Professional Page 2Dani Vainstein DotNetFactory Page 2 of 151DateTime.AddSeconds ( Double ) Method................................................................... 38DateTime.AddTicks ( Long ) Method .......................................................................... 39DateTime.AddYears ( Integer ) Method ....................................................................... 39DateTime.Compare ( DateTime, DateTime ) Method .................................................. 40DateTime.CompareTo ( DateTime ) Method................................................................ 40DateTime.DaysInMonth ( Integer, Integer ) Method.................................................... 41DateTime.Equals ( DateTime ) Method........................................................................ 45DateTime.Equals ( DateTime, DateTime ) Method...................................................... 45DateTime.FromBinary ( Long ) Method....................................................................... 46DateTime.FromFileTime ( Long ) Method................................................................... 47DateTime.FromFileTimeUtc ( Long ) Method ............................................................. 48DateTime.GetTimeFormats Method............................................................................. 49DateTime.GetTimeFormats () Method ......................................................................... 49DateTime.GetTimeFormats ( Char ) Method................................................................ 50DateTime.GetTimeFormats ( IFormatProvider ) Method............................................. 51DateTime.GetTimeFormats ( Char, IFormatProvider ) Method................................... 53DateTime.GetHashCode () Method .............................................................................. 54DateTime.GetTypeCode () Method .............................................................................. 55DateTime.IsDaylightSavingTime () Method ................................................................ 55DateTime.IsLeapYear ( Integer ) Method..................................................................... 56DateTime.op_Addition ( DateTime, TimeSpan ) Method ............................................ 56DateTime.op_Equality ( DateTime, DateTime ) Method ............................................. 57DateTime.op_GreaterThan ( DateTime, DateTime ) Method....................................... 57DateTime.op_GreaterThanOrEqual ( DateTime, DateTime ) Method ......................... 58DateTime.op_Inequality ( DateTime, DateTime ) Method........................................... 58DateTime.op_LessThan ( DateTime, DateTime ) Method ........................................... 59DateTime.op_LessThanOrEqual ( DateTime, DateTime ) Method.............................. 59DateTime.op_Subtraction Method................................................................................ 59DateTime.op_Subtraction ( DateTime, DateTime ) Method ........................................ 59DateTime.op_Subtraction ( DateTime, TimeSpan ) Method........................................ 61DateTime.Parse Method................................................................................................ 61DateTime.Parse ( String ) Method ................................................................................ 62DateTime.Parse ( String, IFormatProvider ) Method.................................................... 63DateTime.Parse ( String, IFormatProvider, DateTimeStyles ) Method........................ 64DateTime.ParseExact Method....................................................................................... 65DateTime.ParseExact ( String, String, IFormatProvider ) Method............................... 66DateTime.ParseExact ( String, String, IFormatProvider, DateTimeStyles ) Method ... 67DateTime.ParseExact ( String, String[], IFormatProvider, DateTimeStyles ) Method. 68DateTime.SpecifyKind ( DateTime, DateTimeKind ) Method..................................... 70DateTime.Subtract Method........................................................................................... 71DateTime.Subtract ( DateTime ) Method ..................................................................... 71DateTime.Subtract ( TimeSpan ) Method..................................................................... 72DateTime.ToFileTime () Method.................................................................................. 73DateTime.ToFileTimeUtc () Method............................................................................ 74DateTime.ToLocalTime () Method............................................................................... 74DateTime.ToLongDateString () Method....................................................................... 75DateTime.ToLongTimeString () Method...................................................................... 77DateTime.ToShortDateString () Method ...................................................................... 77DateTime.ToShortTimeString () Method ..................................................................... 78DateTime.ToString Method .......................................................................................... 79DateTime.ToString () Method ...................................................................................... 79
  • 3. Chapter 14 Scripting Quicktest Professional Page 3Dani Vainstein DotNetFactory Page 3 of 151DateTime.ToString ( IFormatProvider ) Method.......................................................... 82DateTime.ToString ( String ) Method........................................................................... 83DateTime.ToString ( String, IFormatProvider ) Method .............................................. 85DateTime.ToUniversalTime () Method ........................................................................ 86DateTime.TryParse Method.......................................................................................... 86DateTime.TryParse ( String, DateTime ) Method......................................................... 87DateTime.TryParse ( String, IFormatProvider, DateTimeStyles, DateTime ) Method 88DateTime.TryParseExact Method................................................................................. 89DateTime.TryParse ( String, String, IFormatProvider, DateTimeStyles, DateTime )Method .......................................................................................................................... 89DateTime.TryParse ( String, String[], IFormatProvider, DateTimeStyles, DateTime )Method .......................................................................................................................... 90SYSTEM.TIMESPAN STRUCTURE ............................................................................................. 92SYSTEM.TIMESPAN CONTRUCTORS .................................................................................... 92DateTime.TimeSpan ( int64 ) Constructor.................................................................... 92DateTime.TimeSpan ( int32, int32, int32 ) Constructor ............................................... 94DateTime.TimeSpan ( int32, int32, int32, int32 ) Constructor..................................... 95DateTime.TimeSpan ( int32, int32, int32, int32, int32 ) Constructor........................... 96SYSTEM.TIMESPAN FIELDS ................................................................................................. 98TimeSpan.MaxValue Field ........................................................................................... 98TimeSpan.MinValue Field............................................................................................ 99TimeSpan.TicksPerDay Field ....................................................................................... 99TimeSpan.TicksPerHour Field...................................................................................... 99TimeSpan.TicksPerMillisecond Field......................................................................... 100TimeSpan.TicksPerMinute Field ................................................................................ 100TimeSpan.TicksPerSecond Field ................................................................................ 100TimeSpan.Zero Field................................................................................................... 100TIMESPAN PROPERTIES ..................................................................................................... 100TimeSpan.Days Property ............................................................................................ 101TimeSpan.Hours Property........................................................................................... 103TimeSpan.Milliseconds Property................................................................................ 104TimeSpan.Minutes Property ....................................................................................... 104TimeSpan.Seconds Property ....................................................................................... 105TimeSpan.Ticks Property............................................................................................ 105TimeSpan.TotalDays Property.................................................................................... 105TimeSpan.TotalHours Property .................................................................................. 106TimeSpan.TotalMilliseconds Property........................................................................ 106TimeSpan.TotalMinutes Property............................................................................... 107TimeSpan.TotalSeconds Property............................................................................... 107TIMESPAN METHODS ........................................................................................................ 107TimeSpan.Add ( TimeSpan ) Method......................................................................... 109DateTime.Compare ( TimeSpan, TimeSpan ) Method ............................................... 110TimeSpan.CompareTo ( TimeSpan ) Method............................................................. 112TimeSpan.Duration ( ) Method................................................................................... 113TimeSpan.Equals Method........................................................................................... 114TimeSpan.Equals ( TimeSpan ) Method..................................................................... 114TimeSpan.Equals ( TimeSpan, TimeSpan ) Method................................................... 115TimeSpan.FromDays ( Double ) Method.................................................................... 115TimeSpan.FromHours ( Double ) Method.................................................................. 117TimeSpan.FromMilliseconds ( Double ) Method ....................................................... 119TimeSpan.FromMinutes ( Double ) Method............................................................... 121
  • 4. Chapter 14 Scripting Quicktest Professional Page 4Dani Vainstein DotNetFactory Page 4 of 151TimeSpan.FromSeconds ( Double ) Method............................................................... 122TimeSpan.FromTicks ( Long ) Method ...................................................................... 123TimeSpan.GetHashCode ( ) Method........................................................................... 124TimeSpan.Negate ( ) Method...................................................................................... 125TimeSpan.op_Addition ( TimeSpan, TimeSpan ) Method ......................................... 126TimeSpan.op_Equality ( TimeSpan, TimeSpan ) Method.......................................... 128TimeSpan.op_GreaterThan ( TimeSpan, TimeSpan ) Method ................................... 130TimeSpan.op_GreaterThanOrEqual ( TimeSpan, TimeSpan ) Method...................... 130TimeSpan.op_Inequality ( TimeSpan, TimeSpan ) Method ....................................... 130TimeSpan.op_LessThan ( TimeSpan, TimeSpan ) Method........................................ 131TimeSpan.op_LessThanOrEqual ( TimeSpan, TimeSpan ) Method .......................... 131TimeSpan.op_Subtraction ( TimeSpan, TimeSpan ) Method..................................... 132TimeSpan.op_UnaryNegation ( ) Method................................................................... 132TimeSpan.op_UnaryPlus ( ) Method .......................................................................... 133TimeSpan.Parse ( String ) Method.............................................................................. 133TimeSpan.Subtract ( TimeSpan ) Method................................................................... 135TimeSpan.ToString ( String ) Method ........................................................................ 136TimeSpan.TryParse ( String, TimeSpan ) Method...................................................... 136DOTNETFACTORY TASKS ...................................................................................................... 137WORLD CALENDARS ......................................................................................................... 137SYSTEM.COLLECTIONS.ARRAYLIST ................................................................................. 140CALLCHAIN USING SYSTEM.COLLECTIONS.STACK .......................................................... 141APPENDIX 14.A – ENUMERATIONS ........................................................................................ 144System.DateTimeKind Enumeration .......................................................................... 145System.DayOfWeek Enumeration .............................................................................. 145Standard DateTime Format Strings............................................................................. 145Custom DateTime Format Strings .............................................................................. 146System.Globalization.DateTimeStyles Enumeration.................................................. 150DotNetFactoryThe DotNetFactory ObjectEnables you to create an instance of a .NET object, and access its methods andproperties.You can use this object to access the static methods and properties of a class thatdoes not have an instance constructor, for example, System.Environment, as well asa class that does.CreateInstance MethodReturns a COM interface for a .NET object
  • 5. Chapter 14 Scripting Quicktest Professional Page 5Dani Vainstein DotNetFactory Page 5 of 151If you want to use a .NET object as an argument for a method in QuickTest, youmust first create a COM interface for the .NET object using the CreateInstancemethod. Then you pass that interface as the method argument.Set var_CreateInstance =DotNetFactory.CreateInstance (TypeName [,Assembly] [,args])Parameter DescriptionTypeNameThe full name of the object type, for example,System.Windows.Forms.Form.AssemblyOptional. If the assembly is preloaded in the registry, you do not need toenter 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 theGAC (Global Assembly Cache), you can enter the short name, for example,Forms.Note: If you do not pass this argument, QuickTest assumes that theassembly is resident in memory. If QuickTest does not find the assembly,an error message is displayed during the run session.argsOptional. The required arguments, if any, for the specified TypeNameand/or AssemblyA Variant value. Returns the defined instance of the .NET object.QTP DotNetFactoryWhen QTP version 9.0 was released. I have noticed that a new utility object was added,theDotNetFactory object.Since, that period of time, I was working on a web application, I thought myself , thatDotNetFactory is a utility to work with .NET applications, like the DOT.NET ExtensibilityIn QTP Version 9.2, I so the following example in the QTP helpSet var_CreateInstance = _DotNetFactory.CreateInstance("System.Windows.Forms.Form", "System.Windows.Forms")var_CreateInstance.Showwait 2var_CreateInstance.CloseAnd alsoSet var_CreateInstance = DotNetFactory.CreateInstance("System.Environment")msgbox var_CreateInstance.CurrentDirectoryThe first example display an empty windows form. I started to think, why I need to displaya form , during a test run. The second example catch my eye, and when I tried it in qtp, Igot the following result :
  • 6. Chapter 14 Scripting Quicktest Professional Page 6Dani Vainstein DotNetFactory Page 6 of 151"wow!!" I said to my self, nice to know that I can have every single environment value ofthe system, especially SystemDirectory property. The others values, can be retrieved usingstandard VBScript objects and QTP Environment object. So, again … I did not paid attentionand 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 theapplication is a bank system application, I cant show screenshots. But a web table wasdisplayed in the following format :Date AmountTue, 12 Sep 2006 2500$Thu, 12 Oct 2006 2490$Sun, 12 Nov 2006 2475$Tue, 12 Dec 2006 2466$
  • 7. Chapter 14 Scripting Quicktest Professional Page 7Dani Vainstein DotNetFactory Page 7 of 151Fri, 12 Jan 2007 2390$Mon, 12 Feb 2007 2285$My problem here, were the dates. VBScript doesnt able to convert formats, to the specificformat I needed, and beside this, any user can change the display format to : mm/dd/yyyyor mmddyy or ddmmyy etc.dteDate = Cdate( "Tue, 12 Sep 2006" )Because the CDate conversion error, in pure vbscript I need a function like thefollowsOption ExplicitDim arr1, arr2, MyDate, nMonth, dteDateMyDate = Browser("B").Page("P").WebTable("rates").GetCellData(1,1)arr1 = Split( MyDate, "," )arr2 = Split( arr1(1), " " )Select Case arr2(2)Case "Jan" : nMonth = 1Case "Feb" : nMonth = 2Case "Mar" : nMonth = 3Case "Apr" : nMonth = 4Case "May" : nMonth = 5Case "Jun" : nMonth = 6Case "Jul" : nMonth = 7Case "Aug" : nMonth = 8Case "Sep" : nMonth = 9Case "Oct" : nMonth = 10Case "Nov" : nMonth = 11Case "Dec" : nMonth = 12End SelectdteDate = DateSerial(arr2(3), nMonth, arr2(1))msgbox dteDateThis process only to retrieve the first date, than, I have to use the DateAdd function, andanother 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.
  • 8. Chapter 14 Scripting Quicktest Professional Page 8Dani Vainstein DotNetFactory Page 8 of 151The application has hundreds of date fields, and dates fields are very critical for theapplication.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 rememberimmediately of the QTP example about the System.Environment objectSo I tried the follow :Option ExplicitDim DateTimeSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )A little more research, using the MSDN help I got the ultimate date handling functionalityOption ExplicitDim DateTime, SystemDateTime, i, StrSet SystemDateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set DateTime = SystemDateTime.Parse( "Tue, 12 Sep 2006" )For i = 1 To 12
  • 9. Chapter 14 Scripting Quicktest Professional Page 9Dani Vainstein DotNetFactory Page 9 of 151Str = Str & DateTime.AddMonths(i).ToString( "ddd, dd MMM yyyy" ) & vbNewLineNextMsgbox StrSet SystemDateTime = Nothing : Set DateTime = NothingSo, the conclusion of all my research, is that you can use almost any DOT.NET objectsupported by your Dot.Net Framework ( today is version 3 ) , so this chapter ofDotNetFactory will demonstrate only the System.DateTime and System.TimeSpanclasses. In some examples I use The System.Text.TextBuilder class,System.Globalization.CultureInfo class, System.DateTimeKind Enumerator,System.Globalization.Calendar and moreSystem.DateTime StructureRepresents an instant in time, typically expressed as a date and time of day.The DateTime value type represents dates and times with values ranging from 12:00:00midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December31, 9999 A.D. (C.E.)Time values are measured in 100-nanosecond units called ticks, and a particular date is thenumber of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in theGregorianCalendar calendar. For example, a ticks value of 31241376000000000Lrepresents the date, Friday, January 01, 0100 12:00:00 midnight. A DateTime value isalways expressed in the context of an explicit or default calendar.More information can be found in the following link :http://msdn2.microsoft.com/en-us/library/system.datetime.aspxSystem.DateTime FieldsName DescriptionMaxValue 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
  • 10. Chapter 14 Scripting Quicktest Professional Page 10Dani Vainstein DotNetFactory Page 10 of 151DateTime.MaxValue FieldRepresents the largest possible value of DateTime. This field is read-onlyThe value of this constant is equivalent to 00:00:00.0000000, January 1, 0001.DateTime.MinValue FieldRepresents the smallest possible value of DateTime. This field is read-onlyThe value of this constant is equivalent to 23:59:59.9999999, December 31, 9999,exactly one 100-nanosecond tick before 00:00:00, January 1, 10000.System.DateTime ContructorsInitializes a new instance of the DateTime structure.Name DescriptionDateTime (Int64)Initializes a new instance of the DateTime structureto a specified number of ticks.DateTime (Int64, DateTimeKind)Initializes a new instance of the DateTime structureto a specified number of ticks and to CoordinatedUniversal Time (UTC) or local time.DateTime (Int32, Int32, Int32)Initializes a new instance of the DateTime structureto the specified year, month, and day.DateTime (Int32, Int32, Int32,Calendar)Initializes a new instance of the DateTime structureto the specified year, month, and day for thespecified calendar.DateTime (Int32, Int32, Int32,Int32, Int32, Int32)Initializes a new instance of the DateTime structureto the specified year, month, day, hour, minute, andsecond.DateTime (Int32, Int32, Int32,Int32, Int32, Int32, Calendar)Initializes a new instance of the DateTime structureto the specified year, month, day, hour, minute, andsecond for the specified calendar.DateTime (Int32, Int32, Int32,Int32, Int32, Int32, DateTimeKind)Initializes a new instance of the DateTime structureto the specified year, month, day, hour, minute,second, and Coordinated Universal Time (UTC) orlocal time.DateTime (Int32, Int32, Int32,Int32, Int32, Int32, Int32)Initializes a new instance of the DateTime structureto the specified year, month, day, hour, minute,second, and millisecond.DateTime (Int32, Int32, Int32,Int32, Int32, Int32, Int32,Calendar)Initializes a new instance of the DateTime structureto the specified year, month, day, hour, minute,second, and millisecond for the specified calendar.DateTime (Int32, Int32, Int32, Initializes a new instance of the DateTime structure
  • 11. Chapter 14 Scripting Quicktest Professional Page 11Dani Vainstein DotNetFactory Page 11 of 151Int32, Int32, Int32, Int32,DateTimeKind)to the specified year, month, day, hour, minute,second, millisecond, and Coordinated Universal Time(UTC) or local time.DateTime (Int32, Int32, Int32,Int32, Int32, Int32, Int32,Calendar, DateTimeKind)Initializes a new instance of the DateTime structureto the specified year, month, day, hour, minute,second, millisecond, and Coordinated Universal Time(UTC) or local time for the specified calendar.DateTime.DateTime( int64 ) ConstructorInitializes a new instance of the DateTime structure to a specified number of ticks.Set object = DotNetFactory.CreateInstance( "System.DateTime", , ticks )Parameter Descriptionticks A date and time expressed in 100-nanosecond units.System.DateTime objectThe Kind property is initialized to Unspecified.ArgumentOutOfRangeException - ticks is less than MinValue or greater thanMaxValue.The following code example demonstrates one of the DateTime constructorsOption ExplicitDim SDT, dtMax, dtMin, dtCustomDim formatDim SB, CI, ticksformat = "{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 ticksSet 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 _
  • 12. Chapter 14 Scripting Quicktest Professional Page 12Dani Vainstein DotNetFactory Page 12 of 151).TicksSet dtCustom = DotNetFactory.CreateInstance( "System.DateTime", , ticks ) ** ReportingSet SB = DotNetFactory.CreateInstance( "System.Text.StringBuilder" )SB.AppendFormat format, 1, "maximum", dtMax, vbNewLineSB.AppendFormat format, 2, "minimum", dtMin, vbNewLineSB.AppendFormat format, 3, "custom", dtCustom, vbNewLineSB.AppendFormat "The custom datetime is created from {0:N0} ticks.", ticksMsgbox SB.ToString(), vbOkOnly, "DateTime( ticks )" ** CleaningSet SB = Nothing : Set CI = NothingSet dtCustom = Nothing : Set ticks = NothingSet dtMin = Nothing : Set dtMax = Nothing : Set SDT = NothingDateTime.DateTime ( int64, DateTimeKind ) ConstructorInitializes a new instance of the DateTime structure to a specified number of ticks andto Coordinated Universal Time (UTC) or local time.Set object =DotNetFactory.CreateInstance( "System.DateTime", , ticks, kind )Parameter Descriptionticks A date and time expressed in 100-nanosecond units.kindOne of the DateTimeKind values that indicates whether ticks specifies alocal time, Coordinated Universal Time (UTC), or neither.System.DateTime objectArgumentOutOfRangeException - ticks is less than MinValue or greater thanMaxValue.ArgumentException - Kind is not one of the DateTimeKind values.The following code example uses the SpecifyKind method to demonstrate how the Kindproperty influences the ToLocalTime and ToUniversalTime conversion methods.
  • 13. Chapter 14 Scripting Quicktest Professional Page 13Dani Vainstein DotNetFactory Page 13 of 151Option ExplicitConst DATE_PATTERN = "M/d/yyyy hh:mm:ss tt"Dim DateTime, saveNow, saveUtcNow, myDtDim DateTimeKindPrivate Sub DisplayNow( ByVal title, ByRef inputDt )Dim dtStringdtString = inputDt.ToString( DATE_PATTERN )Print title & " " & dtString & ", Kind = " & inputDt.KindEnd SubPublic Sub Display( ByVal title, ByRef inputDt )Dim dispDt, dtStringSet dispDt = inputDt ** Display the original DateTime.dtString = dispDt.ToString( DATE_PATTERN )Print title & " " & dtString & ", Kind = " & dispDt.Kind ** Convert inputDt to local time and display the result. ** If inputDt.Kind is DateTimeKind.Utc, the conversion is performed. ** If inputDt.Kind is DateTimeKind.Local, the conversion is not performed. ** If inputDt.Kind is DateTimeKind.Unspecified, the conversion is ** performed as if inputDt was universal time.Set dispDt = inputDt.ToLocalTime()dtString = dispDt.ToString( DATE_PATTERN )Print "ToLocalTime: " & dtString & ", Kind = " & dispDt.Kind ** Convert inputDt to universal time and display the result. ** If inputDt.Kind is DateTimeKind.Utc, the conversion is not performed. ** If inputDt.Kind is DateTimeKind.Local, the conversion is performed. ** If inputDt.Kind is DateTimeKind.Unspecified, the conversion is ** performed as if inputDt was local time.Set dispDt = inputDt.ToUniversalTime()dtString = dispDt.ToString( DATE_PATTERN )Print "ToUniversalTime: " & dtString & ", Kind = " & dispDt.Kind & vbNewLineEnd Sub DisplaySet DateTime = DotNetFactory.CreateInstance( "System.DateTime" ) ** 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" )
  • 14. Chapter 14 Scripting Quicktest Professional Page 14Dani Vainstein DotNetFactory Page 14 of 151Set myDt = DateTime.SpecifyKind( saveNow, DateTimeKind.Utc )Call Display( "Utc: .............", myDt ) ** 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 = NothingSet saveNow = Nothing : Set saveUtcNow = NothingDateTime.DateTime(Int32, Int32, Int32) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, andday.Set object =DotNetFactory.CreateInstance( "System.DateTime", , year, month, day )Parameter Descriptionyear 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
  • 15. Chapter 14 Scripting Quicktest Professional Page 15Dani Vainstein DotNetFactory Page 15 of 151ArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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 ormore than MaxValue.The following code example uses the SpecifyKind method to demonstrate how the Kindproperty influences the ToLocalTime and ToUniversalTime conversion methods.Option ExplicitDim DateTimeSet DateTime = DotNetFactory.CreateInstance( "System.DateTime", ,1979, 7, 28)MsgBox DateTime.ToString()Set DateTime = NothingDateTime.DateTime(Int32, Int32, Int32, Calendar)ConstructorInitializes a new instance of the DateTime structure to the specified year, month, andday for the specified calendar.Set object = DotNetFactory.CreateInstance("System.DateTime", , year, month, day, calendar )Parameter Descriptionyear 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 objectArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
  • 16. Chapter 14 Scripting Quicktest Professional Page 16Dani Vainstein DotNetFactory Page 16 of 151ArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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 ormore than MaxValue.The time of day for the resulting DateTime is midnight (00:00:00). The Kindproperty is initialized to UnspecifiedThe allowable values for year, month, and day depend on calendar. An exception isthrown if the specified date and time cannot be expressed using calendar.The System.Globalization namespace provides several calendars includingGregorianCalendar and JulianCalendar.The following code example uses the SpecifyKind method to demonstrate how the Kindproperty influences the ToLocalTime and ToUniversalTime conversion methods.Option ExplicitDim DateTimeSet DateTime = DotNetFactory.CreateInstance( "System.DateTime", ,1979, 7, 28)MsgBox DateTime.ToString()Set DateTime = NothingDateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, and second.Set object = DotNetFactory.CreateInstance("System.DateTime", , year, month, day, hour, minute, second )Parameter Descriptionyear 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).
  • 17. Chapter 14 Scripting Quicktest Professional Page 17Dani Vainstein DotNetFactory Page 17 of 151minute The minutes (0 through 59).second The seconds (0 through 59).System.DateTime objectArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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 ormore than MaxValue.The Kind property is initialized to Unspecified.The following code example demonstrates one of the DateTime constructors.Option ExplicitDim DateTimeSet DateTime = _DotNetFactory.CreateInstance( "System.DateTime", ,1979, 7, 28, 12, 23, 32 )Print DateTime.ToStringPrint DateTime.ToString( "F" )Print DateTime.ToString( "R" )Print DateTime.ToString( "G" )Set DateTime = NothingDateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32, Calendar ) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, and second for the specified calendar.Set object = DotNetFactory.CreateInstance(
  • 18. Chapter 14 Scripting Quicktest Professional Page 18Dani Vainstein DotNetFactory Page 18 of 151"System.DateTime", , year, month, day, hour, minute, second, calendar )Parameter Descriptionyear 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 objectArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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 ormore than MaxValue.ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).The Kind property is initialized to Unspecified.The allowable values for year, month, and day depend on calendar. An exception isthrown if the specified date and time cannot be expressed using calendar.The System.Globalization namespace provides several calendars includingGregorianCalendar and JulianCalendar.The following code example demonstrates one of the DateTime constructors.Option ExplicitConst HEBREW_CAL = "System.Globalization.HebrewCalendar"Dim Datetime, calSet cal = DotNetFactory.CreateInstance( HEBREW_CAL, "System" )Set DateTime = DotNetFactory.CreateInstance( _"System.DateTime", , 5767, 3, 14, 4, 10, 5, cal )MsgBox DateTime.ToString( "F" )Set DateTime = Nothing: Set cal = Nothing
  • 19. Chapter 14 Scripting Quicktest Professional Page 19Dani Vainstein DotNetFactory Page 19 of 151DateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32, DateTimeKind ) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, second, and Coordinated Universal Time (UTC) or local time.Set object = DotNetFactory.CreateInstance("System.DateTime", , year, month, day, hour, minute, second, kind )Parameter Descriptionyear 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).kindOne of the DateTimeKind values that indicates whether year, month,day, hour, minute and second specify a local time, CoordinatedUniversal Time (UTC), or neither.System.DateTime objectArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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.ArgumentExceptionThe specified parameters evaluate to less than MinValue or more thanMaxValue.Kind is not one of the DateTimeKind values.
  • 20. Chapter 14 Scripting Quicktest Professional Page 20Dani Vainstein DotNetFactory Page 20 of 151DateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32, Int32 ) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, second and millisecondSet object =DotNetFactory.CreateInstance( "System.DateTime", , _year, month, day, hour, minute, second, millisecond )Parameter Descriptionyear 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 objectArgumentOutOfRangeException.year is less than 1 or greater than 9999month 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.ArgumentExceptionThe specified parameters evaluate to less than MinValue or more thanMaxValue.DateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32, Int32, Calendar ) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, second, and millisecond for the specified calendar.
  • 21. Chapter 14 Scripting Quicktest Professional Page 21Dani Vainstein DotNetFactory Page 21 of 151Set object = DotNetFactory.CreateInstance( "System.DateTime", , _year, month, day, hour, minute, second, millisecond, calendar )Parameter Descriptionyear 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 objectArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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 ormore than MaxValue.ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).The Kind property is initialized to Unspecified.The allowable values for year, month, and day depend on calendar. An exception isthrown if the specified date and time cannot be expressed using calendar.The System.Globalization namespace provides several calendars includingGregorianCalendar and JulianCalendar.DateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32, Int32, DateTimeKind ) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or localtime.
  • 22. Chapter 14 Scripting Quicktest Professional Page 22Dani Vainstein DotNetFactory Page 22 of 151Set object = DotNetFactory.CreateInstance( "System.DateTime", , _year, month, day, hour, minute, second, millisecond, kind )Parameter Descriptionyear 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).kindOne of the DateTimeKind values that indicates whether year, month,day, hour, minute, second, and millisecond specify a local time,Coordinated Universal Time (UTC), or neither.System.DateTime objectArgumentOutOfRangeException .year is less than 1 or greater than 9999month 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.ArgumentExceptionThe specified parameters evaluate to less than MinValue or more thanMaxValue.Kind is not one of the DateTimeKind values.DateTime.DateTime(Int32, Int32, Int32, Int32, Int32,Int32, Int32, Calendar, DateTimeKind ) ConstructorInitializes a new instance of the DateTime structure to the specified year, month, day,hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or localtime for the specified calendar.Set object = DotNetFactory.CreateInstance( "System.DateTime", , _year, month, day, hour, minute, second, millisecond, calendar, kind )
  • 23. Chapter 14 Scripting Quicktest Professional Page 23Dani Vainstein DotNetFactory Page 23 of 151Parameter Descriptionyear 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.kindOne of the DateTimeKind values that indicates whether year, month,day, hour, minute, second, and millisecond specify a local time,Coordinated Universal Time (UTC), or neither.System.DateTime objectArgumentOutOfRangeException .year is not in the range supported by calendar.month is less than 1 or greaterthan 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 than0 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.ArgumentExceptionThe 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 calendarparameter. An exception is thrown if the specified date and time cannot beexpressed using calendar.The System.Globalization namespace provides several calendars includingGregorianCalendar and JulianCalendar.DateTime PropertiesName DescriptionDate 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.
  • 24. Chapter 14 Scripting Quicktest Professional Page 24Dani Vainstein DotNetFactory Page 24 of 151DayOfYear Gets the day of the year represented by this instance.Hour Gets the hour component of the date represented by this instance.KindGets a value that indicates whether the time represented by this instance isbased on local time, Coordinated Universal Time (UTC), or neither.Millisecond Gets the milliseconds component of the date represented by this instance.Minute Gets the minute component of the date represented by this instance.Month Gets the month component of the date represented by this instance.NowGets a DateTime object that is set to the current date and time on thiscomputer, expressed as the local time.Second Gets the seconds component of the date represented by this instance.Ticks Gets the number of ticks that represent the date and time of this instance.TimeOfDay Gets the time of day for this instance.Today Gets the current date.UtcNowGets a DateTime object that is set to the current date and time on thiscomputer, expressed as the Coordinated Universal Time (UTC).Year Gets the year component of the date represented by this instance.DateTime.Date PropertyGets the date component of this instance.object.DateA new DateTime with the same date as this instance, and the time value set to 12:00:00midnight (00:00:00).The following example returns the Date value of Now methodOption ExplicitDim DateTimeDim oToday, oFutureSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set oToday = DateTime.Today()Set oFuture = oToday.AddDays( 7 )Print "Today : " & oToday.Date()Print "Future + 7 : " & oFuture.Date() ** Cleaning objectsSet DateTime = NothingSet oToday = Nothing : Set oFuture = Nothing
  • 25. Chapter 14 Scripting Quicktest Professional Page 25Dani Vainstein DotNetFactory Page 25 of 151DateTime.Day PropertyGets the day of the month represented by this instance.Value = object.DateThe day component, expressed as a value between 1 and 31.The following example returns the Date value of Now methodOption ExplicitDim DateTimeDim oToday, oFutureSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set oToday = DateTime.Today()Set oFuture = oToday.AddHours( 24 )Print "Today : " & oToday.DayPrint "Future + 24h : " & oFuture.Day ** Cleaning objectsSet DateTime = NothingSet oToday = Nothing : Set oFuture = NothingDateTime.DayOfWeek PropertyGets the day of the week represented by this instance.Value = object.DayOfWeek
  • 26. Chapter 14 Scripting Quicktest Professional Page 26Dani Vainstein DotNetFactory Page 26 of 151A DayOfWeek enumerated constant that indicates the day of the week. This propertyvalue ranges from zero, indicating Sunday, to six, indicating Saturday.The following example returns the Date value of Now methodOption ExplicitDim DateTimeDim oToday, oFuture, iSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set oToday = DateTime.Today()For i = 1 To 7Set oFuture = oToday.AddDays( i )Print oFuture.DayOfWeek.GetHashCode & " --> " & oFuture.DayOfWeekNext ** Cleaning objectsSet DateTime = NothingSet oToday = Nothing : Set oFuture = NothingDateTime.DayOfYear PropertyGets the day of the year represented by this instanceobject.DayOfYearThe day of the year, expressed as a value between 1 and 366.The following example returns the Day of The year for TodayMsgbox DotNetFactory.CreateInstance( "System.DateTime" ).Today.DayOfYear
  • 27. Chapter 14 Scripting Quicktest Professional Page 27Dani Vainstein DotNetFactory Page 27 of 151DateTime.Hour PropertyGets the hour component of the date represented by this instance.object.HourThe hour component, expressed as a value between 0 and 23.The following code example demonstrates the Hour property.Option ExplicitDim momentSet moment = DotNetFactory.CreateInstance( _"System.DateTime",, 1999, 1, 13, 3, 57, 32, 11 _)Print "Year --> " & moment.Year ** Year gets 1999.Print "Month --> " & moment.Month ** Month gets 1 (January).Print "Day --> " & moment.Day ** Day gets 13.Print "Hour --> " & moment.Hour ** Hour gets 3.Print "Minute --> " & moment.Minute ** Minute gets 57.Print "Second --> " & moment.Second ** Second gets 32.Print "Millisecond --> " & moment.Millisecond ** Millisecond gets 11.Set moment = NothingDateTime.Kind Property
  • 28. Chapter 14 Scripting Quicktest Professional Page 28Dani Vainstein DotNetFactory Page 28 of 151Gets a value that indicates whether the time represented by this instance is based onlocal time, Coordinated Universal Time (UTC), or neither.object.KindOne of the DateTimeKind values. The default is Unspecified.The following example uses Item to retrieve the FolderItem object representing theWindows folder and filtering the contentOption ExplicitDim saveNow, saveUtcNow, myDtDim DateTimeKindSet DateTimeKind = DotNetFactory.CreateInstance( "System.DateTimeKind" )Set saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).NowPrint "saveNow = " & saveNow.Kind.GetHashCode & " --> " & saveNow.KindSet saveUtcNow = DotNetFactory.CreateInstance( "System.DateTime" ).UtcNowPrint "saveUtcNow = " & saveUtcNow.Kind.GetHashCode & " --> " & saveUtcNow.KindSet myDt = _DotNetFactory.CreateInstance( "System.DateTime" ).SpecifyKind( _saveNow, DateTimeKind.Utc _)Print "myDt = " & myDt.Kind.GetHashCode & " --> " & myDt.KindSet myDt = DotNetFactory.CreateInstance( "System.DateTime" ).SpecifyKind( _saveNow, DateTimeKind.Local _)Print "myDt = " & myDt.Kind.GetHashCode & " --> " & myDt.KindSet myDt = DotNetFactory.CreateInstance( "System.DateTime" ).SpecifyKind( _saveNow, DateTimeKind.Unspecified _)Print "myDt = " & myDt.Kind.GetHashCode & " --> " & myDt.Kind ** Cleaning objectsSet DateTimeKind = Nothing : Set saveNow = NothingSet saveUtcNow = Nothing : Set myDt = Nothing
  • 29. Chapter 14 Scripting Quicktest Professional Page 29Dani Vainstein DotNetFactory Page 29 of 151DateTime.Millisecond PropertyGets the milliseconds component of the date represented by this instance.Value = object.MillisecondThe milliseconds component, expressed as a value between 0 and 999.The following code example demonstrates the Millisecond property.see : DateTime.Hour PropertyDateTime.Minute PropertyGets the minute component of the date represented by this instance.Value = object.MinuteThe minute component, expressed as a value between 0 and 59.The following code example demonstrates the Minute property.see : DateTime.Hour PropertyDateTime.Month PropertyGets the month component of the date represented by this instanceValue = object.MonthThe month component, expressed as a value between 1 and 12.The following code example demonstrates the Minute property.see : DateTime.Hour PropertyDateTime.Now PropertyGets a DateTime object that is set to the current date and time on this computer,
  • 30. Chapter 14 Scripting Quicktest Professional Page 30Dani Vainstein DotNetFactory Page 30 of 151expressed as the local time.Value = object.NowA DateTime whose value is the current local date and time.The following example returns the Now property.Set oNow = DotNetFactory.CreateInstance( "System.DateTime" ).NowDateTime.Second PropertyGets the seconds component of the date represented by this instance.Value = object.SecondThe seconds, between 0 and 59.The following code example demonstrates the Second property.see : DateTime.Hour PropertyDateTime.Ticks PropertyGets the number of ticks that represent the date and time of this instanceValue = object.TicksThe number of ticks that represent the date and time of this instance. The value isbetween MinValue and MaxValue.DateTime.TimeOfDay PropertyGets the time of day for this instance.Value = object.TimeOfDay
  • 31. Chapter 14 Scripting Quicktest Professional Page 31Dani Vainstein DotNetFactory Page 31 of 151A TimeSpan that represents the fraction of the day that has elapsed since midnight.The following example uses Item to retrieve the FolderItem object representing theWindows folder and filtering the contentOption ExplicitDim saveNow, timeSpanSet saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).NowPrint "saveNow = " & saveNowSet timeSpan = saveNow.TimeOfDayPrint "Time since midnight -> Hours : " & _timeSpan.Hours & ", Minutes : " & _timeSpan.Minutes & ", Seconds : " & timeSpan.SecondsSet saveNow = Nothing : Set timeSpan = NothingDateTime.Today PropertyGets the current date..Value = object.TodayA DateTime set to todays date, with the time component set to 00:00:00.The following example returns the Today property.Set oToday = DotNetFactory.CreateInstance( "System.DateTime" ).TodayDateTime.UtcNow PropertyGets a DateTime object that is set to the current date and time on this computer,expressed as the Coordinated Universal Time (UTC).Value = object.UtcNowA DateTime whose value is the current UTC date and time.
  • 32. Chapter 14 Scripting Quicktest Professional Page 32Dani Vainstein DotNetFactory Page 32 of 151Starting with the .NET Framework version 2.0, the return value is a DateTime whoseKind property returns Utc.The following example returns the UtcNow property. DateTime.DateTime( int64,DateTimeKind ) ConstructorDateTime.Year PropertyGets the year component of the date represented by this instance.Value = object.YearThe year, between 1 and 9999The following code example demonstrates the Year property.see : DateTime.Hour PropertyDateTime MethodsName DescriptionAddAdds the value of the specified TimeSpan to the value of thisinstanceAddDays 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.AddMillisecondsAdds the specified number of milliseconds to the value of thisinstance.AddMinutesAdds the specified number of minutes to the value of thisinstance.AddMonthsAdds the specified number of months to the value of thisinstance.AddSecondsAdds the specified number of seconds to the value of thisinstance.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.CompareCompares two instances of DateTime and returns an indication oftheir relative values.CompareToOverloaded. Compares this instance to a specified object or valuetype and returns an indication of their relative values.DaysInMonth Returns the number of days in the specified month and year.Equals Overloaded. Returns a value indicating whether two DateTimeobjects, or a DateTime instance and another object or DateTime
  • 33. Chapter 14 Scripting Quicktest Professional Page 33Dani Vainstein DotNetFactory Page 33 of 151are equal.FromBinaryDeserializes a 64-bit binary value and recreates an originalserialized DateTime object.FromFileTimeConverts the specified Windows file time to an equivalent localtime.FromFileTimeUtcConverts the specified Windows file time to an equivalent UTCtime.GetTimeFormatsOverloaded. Converts the value of this instance to all the stringrepresentations supported by the standard DateTime formatspecifiers.GetHashCode Returns the hash code for this instance.GetTypeCode Returns the TypeCode for value type DateTime.IsDaylightSavingTimeIndicates whether this instance of DateTime is within theDaylight Saving Time range for the current time zoneIsLeapYear Returns an indication whether the specified year is a leap year.op_AdditionAdds a specified time interval to a specified date and time,yielding a new date and time.op_EqualityDetermines whether two specified instances of DateTime areequal.op_GreaterThanDetermines whether one specified DateTime is greater thananother specified DateTime.op_GreaterThanOrEqualDetermines whether one specified DateTime is greater than orequal to another specified DateTime.op_InequalityDetermines whether two specified instances of DateTime are notequal.op_LessThanDetermines whether one specified DateTime is less than anotherspecified DateTime.op_LessThanOrEqualDetermines whether one specified DateTime is less than or equalto another specified DateTime.op_SubtractionOverloaded. Subtracts a specified DateTime or TimeSpan froma specified DateTime.ParseOverloaded. Converts the specified string representation of a dateand time to its DateTime equivalent.ParseExactOverloaded. Converts the specified string representation of a dateand time to its DateTime equivalent. The format of the stringrepresentation must match a specified format exactly.SpecifyKindCreates a new DateTime object that represents the same time asthe specified DateTime, but is designated in either local time,Coordinated Universal Time (UTC), or neither, as indicated by thespecified DateTimeKind value.SubtractOverloaded. Subtracts the specified time or duration from thisinstance.ToBinarySerializes the current DateTime object to a 64-bit binary valuethat subsequently can be used to recreate the DateTime object.ToFileTimeConverts the value of the current DateTime object to a Windowsfile time.
  • 34. Chapter 14 Scripting Quicktest Professional Page 34Dani Vainstein DotNetFactory Page 34 of 151ToFileTimeUtcConverts the value of the current DateTime object to a Windowsfile time.ToLocalTime Converts the value of the current DateTime object to local time.ToLongDateStringConverts the value of the current DateTime object to itsequivalent long date string representation.ToLongTimeStringConverts the value of the current DateTime object to itsequivalent long time string representation.ToShortDateStringConverts the value of the current DateTime object to itsequivalent short date string representation.ToShortTimeStringConverts the value of the current DateTime object to itsequivalent short time string representation.ToStringOverloaded. Overridden. Converts the value of the currentDateTime object to its equivalent string representation.ToUniversalTimeConverts the value of the current DateTime object toCoordinated Universal Time (UTC).TryParseOverloaded. Converts the specified string representation of a dateand time to its DateTime equivalent.TryParseExactOverloaded. Converts the specified string representation of a dateand time to its DateTime equivalent. The format of the stringrepresentation must match a specified format exactly.DateTime.Add ( TimeSpan ) MethodAdds the value of the specified TimeSpan to the value of this instance.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.Set object = instance.Add( value )Parameter Descriptionvalue A TimeSpan that contains the interval to add.A DateTime whose value is the sum of the date and time represented by this instanceand the time interval represented by value.This method does not change the value of this DateTime. Instead, a new DateTimeis returned whose value is the result of this operation.The following code example demonstrates the Add method. It calculates the day of theweek that is 36 days (864 hours) from this moment.
  • 35. Chapter 14 Scripting Quicktest Professional Page 35Dani Vainstein DotNetFactory Page 35 of 151Option ExplicitDim saveNow, duration, answerSet saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).NowSet duration = DotNetFactory.CreateInstance( "System.TimeSpan", ,36, 0, 0, 0 )Set answer = saveNow.Add( duration )MsgBox answer.ToString( "dddd" )Set saveNow = Nothing : Set duration = Nothing : Set answer = NothingDateTime.AddDays ( Double ) MethodAdds the specified number of days to the value of this instance.This method does not change the value of this DateTime. Instead, a new DateTimeis 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 isequivalent to 4 days, 12 hours, 0 minutes, 0 seconds, 0 milliseconds, and 0 ticks.The value parameter is rounded to the nearest millisecond.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.Set dateTime = instance.AddDays( days )Parameter DescriptiondaysA number of whole and fractional days. The value parameter can benegative or positiveA DateTime whose value is the sum of the date and time represented by this instanceand the number of days represented by daysThe following code example demonstrates the AddDays methodOption ExplicitDim saveNowSet saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).Now
  • 36. Chapter 14 Scripting Quicktest Professional Page 36Dani Vainstein DotNetFactory Page 36 of 151Print "Today is --> " & saveNow.ToString( "D" )Print "Tomorrow --> " & saveNow.AddDays( 1 ).ToString( "D" )Print "Yesterday --> " & saveNow.AddDays( -1 ).ToString( "D" )Set saveNow = NothingDateTime.AddHours ( Double ) MethodAdds the specified number of hours to the value of this instance.Set dateTime = instance.AddHours( hours )Parameter Descriptionhoursnumber of whole and fractional hours. The value parameter can benegative or positive.A DateTime whose value is the sum of the date and time represented by this instanceand the number of hours represented by hours.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime. Instead, a new DateTimeis 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 isequivalent to 4 hours, 30 minutes, 0 seconds, 0 milliseconds, and 0 ticks..The value parameter is rounded to the nearest millisecond.DateTime.AddMilliseconds ( Double ) MethodAdds the specified number of milliseconds to the value of this instance.Set object = instance.AddMilliseconds( value )Parameter Description
  • 37. Chapter 14 Scripting Quicktest Professional Page 37Dani Vainstein DotNetFactory Page 37 of 151valueA number of whole and fractional milliseconds. The value parameter canbe negative or positive. Note that this value is rounded to the nearestinteger.A DateTime whose value is the sum of the date and time represented by this instanceand the number of milliseconds represented by value.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime. Instead, a newDateTime 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 isequivalent to 4 milliseconds, and 5000 ticks, where one millisecond = 10000 ticks.The value parameter is rounded to the nearest millisecond.DateTime.AddMinutes ( Double ) MethodAdds the specified number of minutes to the value of this instance.Set object = instance.AddMinutes( minutes )Parameter DescriptionminutesA number of whole and fractional minutes. The value parameter can benegative or positive.A DateTime whose value is the sum of the date and time represented by this instanceand the number of minutes represented by minutes.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime. Instead, a new DateTimeis 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 isequivalent to 4 minutes, 30 seconds, 0 milliseconds, and 0 ticks.The value parameter is rounded to the nearest millisecond.DateTime.AddMonths ( Integer ) MethodAdds the specified number of months to the value of this instance.
  • 38. Chapter 14 Scripting Quicktest Professional Page 38Dani Vainstein DotNetFactory Page 38 of 151Set object = instance.AddMonths( months )Parameter Descriptionmonths 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 instanceand months.ArgumentOutOfRangeExceptionmonths 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 newDateTime is returned whose value is the result of this operation.The AddMonths method calculates the resulting month and year, taking intoaccount leap years and the number of days in a month, then adjusts the day part ofthe resulting DateTime object. If the resulting day is not a valid day in the resultingmonth, 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 objectremains the same as this instance.DateTime.AddSeconds ( Double ) MethodAdds the specified number of seconds to the value of this instance.Set object = instance.AddSeconds( seconds )Parameter DescriptionsecondsA number of whole and fractional seconds. The value parameter can benegative or positive.A DateTime whose value is the sum of the date and time represented by this instanceand the number of seconds represented by seconds.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime. Instead, a new DateTimeis returned whose value is the result of this operation.
  • 39. Chapter 14 Scripting Quicktest Professional Page 39Dani Vainstein DotNetFactory Page 39 of 151A The fractional part of value is the fractional part of a second. For example, 4.5 isequivalent to 4 seconds, 500 milliseconds, and 0 ticks.The value parameter is rounded to the nearest millisecond.DateTime.AddTicks ( Long ) MethodAdds the specified number of ticks to the value of this instance.Set object = instance.AddTicks( ticks )Parameter DescriptionticksA number of 100-nanosecond ticks. The value parameter can be positiveor negative.A DateTime whose value is the sum of the date and time represented by thisinstance and the time represented by ticks.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime. Instead, a new DateTimeis returned whose value is the result of this operation.DateTime.AddYears ( Integer ) MethodAdds the specified number of years to the value of this instance.Set object = instance.AddYears( years )Parameter Descriptionyears 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 instanceand the number of years represented by years.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.
  • 40. Chapter 14 Scripting Quicktest Professional Page 40Dani Vainstein DotNetFactory Page 40 of 151This method does not change the value of this DateTime. Instead, a new DateTimeis 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 sameas this instance.DateTime.Compare ( DateTime, DateTime ) MethodCompares two instances of DateTime and returns an indication of their relative values.returnValue = instance.Compare( dt1, dt2 )Parameter Descriptiondt1 The first DateTime.dt2 The second DateTime.A signed number indicating the relative values of dt1 and dt2Less than zero - dt1 is less than dt2.Zero - dt1 equals dt2Greater than zero - dt1 is greater than dt2.Before comparing DateTime objects, insure that the objects represent times in thesame time zone.The following code example demonstrates Compare.Option ExplicitDim dt1, dt2, DateTimeSet dt1 = DotNetFactory.CreateInstance( "System.DateTime", ,100 )Set dt2 = DotNetFactory.CreateInstance( "System.DateTime", ,300 )Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" )If DateTime.Compare( dt1, dt2 ) > 0 ThenPrint "dt1 > dt2"End IfIf DateTime.Compare( dt1, dt2 ) = 0 ThenPrint "dt1 = dt2"End IfIf DateTime.Compare( dt1, dt2 ) < 0 ThenPrint "dt1 < dt2"End IfDateTime.CompareTo ( DateTime ) Method
  • 41. Chapter 14 Scripting Quicktest Professional Page 41Dani Vainstein DotNetFactory Page 41 of 151Compares this instance to a specified DateTime object and returns an indication of theirrelative values.instance.CompareTo( value )Parameter Descriptionvalue 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 valueZero - This instance is equal to value.Greater than zero - This instance is greater than value.This method implements the System.IComparable interface and performs slightlybetter than the DateTime.CompareTo method because it does not have to convertthe value parameter to an object.Before comparing DateTime objects, insure that the objects represent times in thesame time zone.The following code example demonstrates the CompareTo method.Option ExplicitDim DateTime, thDayDim compareValueSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set thDay = DotNetFactory.CreateInstance( _System.DateTime", , DateTime.Today.Year, 7, 28)compareValue = Cint( thDay.CompareTo( DateTime.Today ) )If compareValue < 0 ThenPrint thDay.ToString( "d" ) & " is in the past."ElseIf compareValue = 0 ThenPrint thDay.ToString( "d" ) & " is today!"ElsePrint thDay.ToString( "d" ) & " has not come yet."End IfDateTime.DaysInMonth ( Integer, Integer ) MethodReturns the number of days in the specified month and year.This method implements the System.IComparable interface and performs slightlybetter than the DateTime.CompareTo method because it does not have to convertthe value parameter to an object.
  • 42. Chapter 14 Scripting Quicktest Professional Page 42Dani Vainstein DotNetFactory Page 42 of 151Before comparing DateTime objects, insure that the objects represent times in thesame time zone.returnValue = instance.DaysInMonth( year, month )Parameter Descriptionyear 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 2for February, the return value is 28 or 29 depending upon whether year is a leapyear.ArgumentOutOfRangeExceptionmonth is less than 1 or greater than 12.year is less than 1 or greater than 9999.The following code example demonstrates the DaysInMonth method.Option ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim DateTime, InfoDim arrInfo, i, nMonthPrivate Sub PrintData( ByVal info, ByRef DateTime, ByVal monthIndex )Const FMT = "{0} - {1} --> {2} has {3} Days."Dim monthStr, engName, nativeName, daysInMonDim sbmonthStr= info.DateTimeFormat.MonthNames.GetValue( monthIndex - 1 )engName = info.EnglishNamenativeName = info.NativeNamedaysInMon= DateTime.DaysInMonth( DateTime.Today.Year, monthIndex )Set sb = DotNetFactory.CreateInstance( "System.Text.StringBuilder" )sb.AppendFormat FMT, engName, nativeName, monthStr, daysInMonPrint sb.ToStringSet sb = NothingEnd SubSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )arrInfo = Array( "es-AR", "hi-IN", "de-DE", "fi-FI" )For i = LBound( arrInfo ) To UBound( arrInfo )Set info = DotNetFactory.CreateInstance( CULTURE_INFO, "System", arrInfo( i ) )For nMonth = 1 To 12Call PrintData( info, DateTime, nMonth )NextNext
  • 43. Chapter 14 Scripting Quicktest Professional Page 43Dani Vainstein DotNetFactory Page 43 of 151Set Info = Nothing : Set DateTime = Nothing
  • 44. Chapter 14 Scripting Quicktest Professional Page 44Dani Vainstein DotNetFactory Page 44 of 151
  • 45. Chapter 14 Scripting Quicktest Professional Page 45Dani Vainstein DotNetFactory Page 45 of 151DateTime.Equals ( DateTime ) MethodReturns a value indicating whether this instance is equal to the specified DateTimeinstance.returnValue = instance.Equals( value )Parameter Descriptionvalue A DateTime instance to compare to this instance.true if the value parameter equals the value of this instance; otherwise, false.This method implements the System.IEquatable interface, and performs slightlybetter than the Equals method because the value parameter does not have to beconverted to an object.The following code example demonstrates the Equals method.Option ExplicitDim one, two, threeDim resultSet one = DotNetFactory.CreateInstance( "System.DateTime" ).UtcNowSet two = DotNetFactory.CreateInstance( "System.DateTime" ).NowSet three = oneresult = one.Equals(two)Print "The result of comparing DateTime object one and two is: " & resultresult = one.Equals(three)Print "The result of comparing DateTime object one and three is: " & resultSet one = Nothing : Set two = Nothing : Set three = NothingDateTime.Equals ( DateTime, DateTime ) MethodReturns a value indicating whether two instances of DateTime are equal.ReturnValue = instance.Equals( t1, t2 )
  • 46. Chapter 14 Scripting Quicktest Professional Page 46Dani Vainstein DotNetFactory Page 46 of 151Parameter Descriptiont1 The first DateTime instance.t2 The second DateTime instance.true if the two DateTime values are equal; otherwise, false.This method implements the System.IEquatable interface, and performsslightly better than the Equals method because the value parameter doesnot have to be converted to an object.The following code example demonstrates the Equals method.Option ExplicitDim today1, today2, tomorrow, DateTimeDim todayEqualsToday, todayEqualsTomorrowSet DateTime = DotNetFactory.CreateInstance("System.DateTime")Set today1 = DotNetFactory.CreateInstance("System.DateTime",, DateTime.Today.Ticks )Set today2 = DotNetFactory.CreateInstance("System.DateTime",, DateTime.Today.Ticks )Set tomorrow = DotNetFactory.CreateInstance( "System.DateTime",, _DateTime.Today.AddDays(1).Ticks _) ** todayEqualsToday gets true.todayEqualsToday = DateTime.Equals( today1, today2 ) ** todayEqualsTomorrow gets false.todayEqualsTomorrow = DateTime.Equals(today1, tomorrow)Set today1 = Nothing : Set today2 = Nothing : Set tomorrow = NothingSet DateTime = NothingDateTime.FromBinary ( Long ) MethodDeserializes a 64-bit binary value and recreates an original serialized DateTime objectinstance.FromBinary( dateData )Parameter DescriptiondateDataA 64-bit signed integer that encodes the Kind property in a 2-bit fieldand the Ticks property in a 62-bit fieldA DateTime object that is equivalent to the DateTime object that was serialized bythe ToBinary method
  • 47. Chapter 14 Scripting Quicktest Professional Page 47Dani Vainstein DotNetFactory Page 47 of 151ArgumentException - dateData is less than MinValue or greater than MaxValue.Use the ToBinary method to convert the value of the current DateTime object to abinary value. Subsequently, use the binary value and the FromBinary method torecreate 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. Ifa local DateTime object is serialized in one time zone by the ToBinary method anddeserialized in a different time zone by the FromBinary method, the local timerepresented by the resulting DateTime object is automatically adjusted to thesecond time zone.For example, consider a DateTime object that represents a local time of 3 P.M. Anapplication executing in a western time zone uses the ToBinary method to convertthat DateTime object to a binary value, then another application executing in a timezone three hours east of the original one uses the FromBinary method to convertthe binary value to a new DateTime object. The value of the new DateTime objectis 6 P.M., which represents the same point in time as the original 3 P.M. value, but isadjusted to local time in the eastern time zone.DateTime.FromFileTime ( Long ) MethodConverts the specified Windows file time to an equivalent local time.Set object = instance.FromFileTime( fileTime )Parameter DescriptionfileTime A Windows file time expressed in ticks.A DateTime object that represents a local time equivalent to the date and timerepresented by the fileTime parameter.ArgumentOutOfRangeException - fileTime is less than 0 or represents a time greaterthan MaxValue.A Windows file time is a 64-bit value that represents the number of 100-nanosecondintervals 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 anapplication 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 DateTimewhose Kind property is Local.The following code example demonstrates the FromFileTime method.Option Explicit
  • 48. Chapter 14 Scripting Quicktest Professional Page 48Dani Vainstein DotNetFactory Page 48 of 151Dim dteNow, DateTimeDim fCreationTime, fAge, LongNumSet LongNum = DotNetFactory.CreateInstance( "System.Int64" )Set LongNum = LongNum.Parse( "126879894987978697" )Set dteNow = DotNetFactory.CreateInstance( "System.DateTime" ).NowSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set fCreationTime = DateTime.FromFileTime( LongNum )Set fAge = dteNow.Subtract( fCreationTime )Print fAge.Days & _" Days, " & fAge.Hours & " Hours, and " & fAge.Minutes & " Minutes."Print "TotalDays --> " & fAge.TotalDaysSet fAge = Nothing : Set fCreationTime = Nothing : Set dteNow = NothingSet LongNum = NothingDateTime.FromFileTimeUtc ( Long ) MethodConverts the specified Windows file time to an equivalent UTC time.Set object = instance.FromFileTimeUtc( fileTime )Parameter DescriptionfileTime A Windows file time expressed in ticks.A DateTime object that represents a UTC time equivalent to the date and timerepresented by the fileTime parameterArgumentOutOfRangeException - fileTime is less than 0 or represents a time greaterthan MaxValue.A Windows file time is a 64-bit value that represents the number of 100-nanosecondintervals 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 anapplication 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 DateTimewhose Kind property is Utc.
  • 49. Chapter 14 Scripting Quicktest Professional Page 49Dani Vainstein DotNetFactory Page 49 of 151DateTime.GetTimeFormats MethodName DescriptionGetTimeFormats()Converts the value of this instance to all the stringrepresentations supported by the standard DateTimeformat specifiers.DateTime.GetDateTimeFormats(Char)Converts the value of this instance to all the stringrepresentations supported by the specified standardDateTime format specifier.DateTime.GetDateTimeFormats(IFormatProvider)Converts the value of this instance to all the stringrepresentations supported by the standard DateTimeformat specifiers and the specified culture-specificformatting information.DateTime.GetDateTimeFormats(Char, IFormatProvider)Converts the value of this instance to all the stringrepresentations supported by the specified standardDateTime format specifier and culture-specificformatting information.DateTime.GetTimeFormats () MethodConverts the value of this instance to all the string representations supported by thestandard DateTime format specifiers.Set objectArray = instance.GetTimeFormats()A string array where each element is the representation of the value of this instanceformatted with one of the standard DateTime formatting specifiers.Each element of the return value is formatted using information from the currentculture. For more information about culture-specific formatting information for thecurrent culture, see CultureInfo.CurrentCulture.For For more information about the standard formatting specifiershttp://msdn2.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspxThe following code example demonstrates the GetDateTimeFormats method.Option ExplicitDim july28Formats, july28Dim nFormatSet july28 = DotNetFactory.CreateInstance( _"System.DateTime",, 1979, 7, 28, 5, 23, 15, 16 _)Set july28Formats = july28.GetDateTimeFormats() ** Print out july28 in all DateTime formats using the default culture.
  • 50. Chapter 14 Scripting Quicktest Professional Page 50Dani Vainstein DotNetFactory Page 50 of 151For nFormat = 0 To july28Formats.Length - 1Print july28Formats.GetValue( CLng( nFormat ) )NextSet july28Formats = Nothing: Set july28 = NothingDateTime.GetTimeFormats ( Char ) MethodConverts the value of this instance to all the string representations supported by thespecified standard DateTime format specifier.Set objectArray = instance.GetTimeFormats( format )Parameter Descriptionformat A Standard DateTime format string or a Custom DateTime Format String
  • 51. Chapter 14 Scripting Quicktest Professional Page 51Dani Vainstein DotNetFactory Page 51 of 151A string array where each element is the representation of the value of this instanceformatted with the format standard DateTime formatting specifier.Each element of the return value is formatted using information from the currentculture. For more information about culture-specific formatting information for thecurrent culture, see CultureInfo.CurrentCulture.For For more information about the standard formatting specifiershttp://msdn2.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspxThe following code example demonstrates the GetDateTimeFormats method.Option ExplicitDim july28, sysCharDim nFormatSet july28 = DotNetFactory.CreateInstance( _"System.DateTime",, 1979, 7, 28, 5, 23, 15, 16 _)Set sysChar = DotNetFactory.CreateInstance( "System.Char" ).Parse( "R" ) ** Get the RFC1123 date formatsSet July28Formats = july28.GetDateTimeFormats( sysChar ) ** Print out july28 in various RFC1123 formatsFor nFormat = 0 To July28Formats.Length - 1Print July28Formats.GetValue( CLng( nFormat ) )NextSet July28Formats = Nothing : Set july28 = Nothing : Set sysChar = NothingDateTime.GetTimeFormats ( IFormatProvider ) MethodConverts the value of this instance to all the string representations supported by thestandard DateTime format specifiers and the specified culture-specific formattinginformation.Set objectArray = instance.GetTimeFormats( provider )Parameter DescriptionproviderAn IFormatProvider that supplies culture-specific formattinginformation about this instance.
  • 52. Chapter 14 Scripting Quicktest Professional Page 52Dani Vainstein DotNetFactory Page 52 of 151A string array where each element is the representation of the value of this instanceformatted with one of the standard DateTime formatting specifiers.Each element of the return value is formatted using culture-specific informationsupplied by provider.For For more information about the standard formatting specifiershttp://msdn2.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspxThe following code example demonstrates the GetDateTimeFormats method.Option ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim arabicJuly28Formats, july28, cultureDim nFormatSet july28 = DotNetFactory.CreateInstance( _"System.DateTime",, 1979, 7, 28, 5, 23, 15, 16 _)Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "ar-EG", True ) ** Get the short date formats using the "ar-EG" culture.Set arabicJuly28Formats = july28.GetDateTimeFormats( culture )Print "Starting DateTiume Formats for --> " & _culture.EnglishName & ", " & culture.NativeNameFor nFormat = 0 To arabicJuly28Formats.Length – 1 Step 2Print arabicJuly28Formats.GetValue( CLng( nFormat ) )NextSet arabicJuly28Formats = Nothing : Set july28 = Nothing : Set culture = Nothing
  • 53. Chapter 14 Scripting Quicktest Professional Page 53Dani Vainstein DotNetFactory Page 53 of 151DateTime.GetTimeFormats ( Char, IFormatProvider )MethodConverts the value of this instance to all the string representations supported by thestandard DateTime format specifiers and the specified culture-specific formattinginformation.Set objectArray = instance.GetTimeFormats( format, provider )Parameter Descriptionformat A Standard DateTime format string or a Custom DateTime Format StringproviderAn IFormatProvider that supplies culture-specific formattinginformation about this instance.A string array where each element is the representation of the value of this instanceformatted with one of the standard DateTime formatting specifiers.Each element of the return value is formatted using culture-specific informationsupplied by provider.For For more information about the standard formatting specifiers
  • 54. Chapter 14 Scripting Quicktest Professional Page 54Dani Vainstein DotNetFactory Page 54 of 151http://msdn2.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspxThe following code example demonstrates the GetDateTimeFormats method.Option ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim frenchJuly28Formats, july28, culture, sysCharDim nFormatSet july28 = DotNetFactory.CreateInstance( _"System.DateTime",, 1979, 7, 28, 5, 23, 15, 16 _)Set sysChar = DotNetFactory.CreateInstance( "System.Char" ).Parse( "f" )Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "fr-FR", True ) ** Get the short date formats using the "fr-FR" culture.Set frenchJuly28Formats = july28.GetDateTimeFormats( sysChar, culture ) ** Print out july28 in various formats using "fr-FR" culture.Print "Starting fr-FR formats..."For nFormat = 0 To frenchJuly28Formats.Length - 1Print frenchJuly28Formats.GetValue( CLng( nFormat ) )NextSet frenchJuly28Formats = Nothing : Set july28 = NothingDateTime.GetHashCode () MethodReturns the hash code for this instance.returnValue = instance.GetHashCode()
  • 55. Chapter 14 Scripting Quicktest Professional Page 55Dani Vainstein DotNetFactory Page 55 of 151A 32-bit signed integer hash code.The following code example demonstrates the GetHashCode method.Option ExplicitDim SystemTimeSet SystemTime = DotNetFactory.CreateInstance( "System.DateTime" ).TodayPrint "GetTypeCode --> " & SystemTime.GetTypeCodePrint "GetType --> " & SystemTime.GetTypePrint "GetHashCode.GetType --> " & SystemTime.GetHashCode.GetTypePrint "GetHashCode --> " & SystemTime.GetHashCodeSet SystemTime = NothingDateTime.GetTypeCode () MethodReturns the TypeCode for value type DateTime.instance.GetTypeCode()The enumerated constant, TypeCode.DateTime.The following code example demonstrates the GetTypeCode method.DateTime.GetHashCode() MethodDateTime.IsDaylightSavingTime () MethodIndicates whether this instance of DateTime is within the Daylight Saving Time rangefor the current time zone.instance.IsDaylightSavingTime ()true if Kind is Local or Unspecified and the value of this instance of DateTime iswithin the Daylight Saving Time range for the current time zone. false if Kind is Utc.
  • 56. Chapter 14 Scripting Quicktest Professional Page 56Dani Vainstein DotNetFactory Page 56 of 151DateTime.IsLeapYear ( Integer ) MethodReturns an indication whether the specified year is a leap year.instance.IsLeapYear( year )Parameter Descriptionyear A 4-digit year.true if year is a leap year; otherwise, false.ArgumentOutOfRangeException - year is less than 1 or greater than 9999.year is specified as a 4-digit base 10 number; for example, 1996.DateTime.op_Addition ( DateTime, TimeSpan ) MethodAdds a specified time interval to a specified date and time, yielding a new date and time.instance.op_Addition( d, t )Parameter Descriptiond A DateTime objectt A TimeSpan objectA DateTime that is the sum of the values of d and t.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.The following code example demonstrates the addition operator.Option ExplicitDim dTime, tSpan, result, DateTimeSet dTime = DotNetFactory.CreateInstance( "System.DateTime",,1980, 8, 5 ) ** tSpan is 17 days, 4 hours, 2 minutes and 1 second.
  • 57. Chapter 14 Scripting Quicktest Professional Page 57Dani Vainstein DotNetFactory Page 57 of 151Set tSpan = DotNetFactory.CreateInstance( "System.TimeSpan",,17, 4, 2, 1 ) ** Result gets 8/22/1980 4:02:01 AM.Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set result = DateTime.op_Addition( dTime, tSpan )Msgbox result.ToString( "G" )Set result = Nothing : Set tSpan = Nothing : Set dTime = NothingDateTime.op_Equality ( DateTime, DateTime ) MethodDetermines whether two specified instances of DateTime are equal.instance.op_Equality( d1, d2 )Parameter Descriptiond1 A DateTime objectd2 A DateTime objecttrue if d1 and d2 represent the same date and time; otherwise, false.The following code example demonstrates the equality operator.Option ExplicitDim april19, otherDateDim areEqualSet april19 = DotNetFactory.CreateInstance( "System.DateTime",,2001, 4, 19 )Set otherDate = DotNetFactory.CreateInstance( "System.DateTime",,1991, 6, 5 ) ** areEqual gets false.areEqual = DotNetFactory.CreateInstance( _"System.DateTime").op_Equality( april19, otherDate )Set otherDate = DotNetFactory.CreateInstance( "System.DateTime",,2001, 4, 19) ** areEqual gets true.areEqual = DotNetFactory.CreateInstance( _"System.DateTime").op_Equality( april19, otherDate )Set otherDate = Nothing : Set april19 = NothingDateTime.op_GreaterThan ( DateTime, DateTime ) Method
  • 58. Chapter 14 Scripting Quicktest Professional Page 58Dani Vainstein DotNetFactory Page 58 of 151Determines whether one specified DateTime is greater than another specifiedDateTime.instance.op_GreaterThan( t1, t2 )Parameter Descriptiont1 A DateTime objectt2 A DateTime objecttrue if t1 is greater than t2; otherwise, false.DateTime.op_GreaterThanOrEqual ( DateTime, DateTime )MethodDetermines whether one specified DateTime is greater than or equal to anotherspecifiedinstance.op_GreaterThanOrEqual( t1, t2 )Parameter Descriptiont1 A DateTime objectt2 A DateTime objecttrue if t1 is greater than or equal to t2; otherwise, false.DateTime.op_Inequality ( DateTime, DateTime ) MethodDetermines whether two specified instances of DateTime are not equal.instance.op_Equality( d1, d2 )Parameter Descriptiond1 A DateTime objectd2 A DateTime object
  • 59. Chapter 14 Scripting Quicktest Professional Page 59Dani Vainstein DotNetFactory Page 59 of 151true if d1 and d2 do not represent the same date and time; otherwise, false.DateTime.op_LessThan ( DateTime, DateTime ) MethodDetermines whether one specified DateTime is less than another specified DateTimeinstance.op_LessThan( t1, t2 )Parameter Descriptiont1 A DateTime objectt2 A DateTime objecttrue if t1 is less than t2; otherwise, false.DateTime.op_LessThanOrEqual ( DateTime, DateTime )MethodDetermines whether one specified DateTime is less than or equal to another specifiedDateTimeinstance.op_LessThanOrEqual( t1, t2 )Parameter Descriptiont1 A DateTime objectt2 A DateTime objecttrue if t1 is less than or equal to t2; otherwise, false.DateTime.op_Subtraction MethodName DescriptionDateTime.op_Subtraction(DateTime, DateTime)Subtracts a specified date and time from anotherspecified date and time, yielding a time interval.DateTime.op_Subtraction(DateTime, TimeSpan)Subtracts a specified time interval from a specifieddate and time, yielding a new date and time.DateTime.op_Subtraction ( DateTime, DateTime ) Method
  • 60. Chapter 14 Scripting Quicktest Professional Page 60Dani Vainstein DotNetFactory Page 60 of 151Subtracts a specified date and time from another specified date and time,yielding a time interval.instance.op_Subtract( d1, d2 )Parameter Descriptiond1 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.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.The following code example demonstrates the equality operator.Option ExplicitDim date1, date2, date3, date4, date5Dim diff1, diff2, SystemDateTimeSet SystemDateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set date1 = DotNetFactory.CreateInstance( "System.DateTime",,1996, 6, 3, 22, 15, 0 )Print "date1 --> " & date1.ToString( "G" )Set date2 = DotNetFactory.CreateInstance( "System.DateTime",,1996, 12, 6, 13, 2, 0 )Print "date2 --> " & date2.ToString( "G" )Set date3 = DotNetFactory.CreateInstance( "System.DateTime",,1996, 10, 12,8, 42, 0 )Print "date3 --> " & date3.ToString( "G" ) ** diff1 gets 185 days, 14 hours, and 47 minutes.Set diff1 = date2.Subtract( date1 )Print "diff1 --> " & diff1.ToString() ** date4 gets 4/9/1996 5:55:00 PM.Set date4 = date3.Subtract( diff1 )Print "date4 --> " & date4.ToString() ** diff2 gets 55 days 4 hours and 20 minutes.Set diff2 = SystemDateTime.op_Subtraction( date2, date3 )Print "diff2 --> " & diff2.ToString() ** date5 gets 4/9/1996 5:55:00 PM.Set date5 = SystemDateTime.op_Subtraction( date1, diff2 )Print "date5 --> " & date5.ToString()Set date1 = Nothing : Set date2 = Nothing : Set date3 = NothingSet date4 = Nothing : Set date5 = Nothing : Set diff1 = NothingSet SystemDateTime = Nothing : Set diff2 = NothingSet
  • 61. Chapter 14 Scripting Quicktest Professional Page 61Dani Vainstein DotNetFactory Page 61 of 151DateTime.op_Subtraction ( DateTime, TimeSpan ) MethodSubtracts a specified time interval from a specified date and time, yielding a new dateand time.instance.op_Subtract( d, t )Parameter Descriptiond A DateTime.t A TimeSpan.A DateTime whose value is the value of d minus the value of t.This method subtracts the ticks value of t from the ticks value of d.ArgumentOutOfRangeException - The resulting DateTime is less than . MinValue orgreater than MaxValue.The following code example demonstrates the equality operator. SeeDateTime.op_Subtraction( DateTime, DateTime ) MethodDateTime.Parse MethodName DescriptionDateTime.Parse (String)Converts the specified string representation of a dateand time to its DateTime equivalent.DateTime.Parse (String,IFormatProvider)Converts the specified string representation of a dateand time to its DateTime equivalent using thespecified culture-specific format information.DateTime.Parse (String, Converts the specified string representation of a date
  • 62. Chapter 14 Scripting Quicktest Professional Page 62Dani Vainstein DotNetFactory Page 62 of 151IFormatProvider, DateTimeStyles) and time to its DateTime equivalent using thespecified culture-specific format information andformatting styleDateTime.Parse ( String ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent.instance.Parse( s )Parameter Descriptions string containing a date and time to convert.A DateTime equivalent to the date and time contained in s.ArgumentNullException - s is a null reference (Nothing in Visual Basic).FormatException - s does not contain a valid string representation of a date andtime.The string s is parsed using formatting information in the currentDateTimeFormatInfo object, which is supplied implicitly by the current threadculture.This method attempts to parse s completely and avoid throwing FormatException. Itignores unrecognized data if possible and fills in missing month, day, and yearinformation with the current time. If s contains only a date and no time, this methodassumes 12:00 midnight. Any leading, inner, or trailing white space character in s isignored. The date and time can be bracketed with a pair of leading and trailingNUMBER SIGN characters (#, U+0023), and can be trailed with one or more NULLcharacters (U+0000).The s parameter must contain the representation of a date and time in one of theformats described in the DateTimeFormatInfo topicThe following code example demonstrates the Parse method.Option ExplicitDim myDateTimeValue, myDateTimemyDateTimeValue = "2/16/1992 12:15:12"Set myDateTime = DotNetFactory.CreateInstance( _"System.DateTime" ).Parse(myDateTimeValue)Msgbox "myDateTime = " & myDateTime.ToString()Set myDateTime = Nothing
  • 63. Chapter 14 Scripting Quicktest Professional Page 63Dani Vainstein DotNetFactory Page 63 of 151DateTime.Parse ( String, IFormatProvider ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified culture-specific format information.instance.Parse( s, provider )Parameter Descriptions string containing a date and time to convert.providerAn IFormatProvider that supplies culture-specific format informationabout s.A DateTime equivalent to the date and time contained in s as specified by provider.ArgumentNullException - s is a null reference (Nothing in Visual Basic).FormatException - s does not contain a valid string representation of a date andtime.The string s is parsed using formatting information in the DateTimeFormatInfoobject that is supplied either explicitly or implicitly by the provider parameter.This method attempts to parse s completely and avoid throwing FormatException. Itignores unrecognized data if possible and fills in missing month, day, and yearinformation with the current time. If s contains only a date and no time, this methodassumes 12:00 midnight. Any leading, inner, or trailing white space character in s isignored. The date and time can be bracketed with a pair of leading and trailingNUMBER SIGN characters (#, U+0023), and can be trailed with one or more NULLcharacters (U+0000).The s parameter must contain the representation of a date and time in one of theformats described in the DateTimeFormatInfo topicThe provider parameter supplies culture-specific date and time formattinginformation. For example, the names of the days of the week in a particularlanguage, or the preferred presentation order of the month, day, and year. Ifprovider is a null reference (Nothing in Visual Basic), the current culture is used.If you parse a date and time string generated for a custom culture, use theParseExact method instead of the Parse method to improve the probability thatthe parse operation will succeed. A custom culture date and time string can becomplicated, and therefore difficult to parse. The Parse method attempts to parse astring with several implicit parse patterns, all of which might fail. The ParseExact
  • 64. Chapter 14 Scripting Quicktest Professional Page 64Dani Vainstein DotNetFactory Page 64 of 151method, in contrast, requires you to explicitly designate one or more exact parsepatterns that are likely to succeed.The following code example demonstrates the Parse method.Option ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim myDateTimeFrenchValue, myDateTimeFrench, culturemyDateTimeFrenchValue = "16/02/1992 12:15:12"Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "fr-FR", True )Set myDateTimeFrench = DotNetFactory.CreateInstance( _"System.DateTime" ).Parse( myDateTimeFrenchValue, culture )MsgBox myDateTimeFrench.ToString()Set myDateTimeFrench = Nothing : Set culture = NothingDateTime.Parse ( String, IFormatProvider, DateTimeStyles) MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified culture-specific format information and formatting style.instance.Parse( s, provider, styles )Parameter Descriptions string containing a date and time to convert.providerAn IFormatProvider that supplies culture-specific format informationabout s.stylesA bitwise combination of DateTimeStyles values that indicates thepermitted format of s. A typical value to specify is None.A DateTimeequivalent to the date and time contained in s as specified by providerand styles.ArgumentNullException - s is a null reference (Nothing in Visual Basic).FormatException - s does not contain a valid string representation of a date andtime.ArgumentException - styles contains an invalid combination of DateTimeStyles
  • 65. Chapter 14 Scripting Quicktest Professional Page 65Dani Vainstein DotNetFactory Page 65 of 151values. For example, both AssumeLocal and AssumeUniversal.The string s is parsed using formatting information in the DateTimeFormatInfoobject that is supplied either explicitly or implicitly by the provider parameter.This method attempts to parse s completely and avoid throwing FormatException. Itignores unrecognized data if possible and fills in missing month, day, and yearinformation with the current time. If s contains only a date and no time, this methodassumes 12:00 midnight. Any leading, inner, or trailing white space character in s isignored. The date and time can be bracketed with a pair of leading and trailingNUMBER SIGN characters (#, U+0023), and can be trailed with one or more NULLcharacters (U+0000).The s parameter must contain the representation of a date and time in one of theformats described in the DateTimeFormatInfo topicThe provider parameter supplies culture-specific date and time formattinginformation. For example, the names of the days of the week in a particularlanguage, or the preferred presentation order of the month, day, and year. Ifprovider is a null reference (Nothing in Visual Basic), the current culture is used.If you parse a date and time string generated for a custom culture, use theParseExact method instead of the Parse method to improve the probability thatthe parse operation will succeed. A custom culture date and time string can becomplicated, and therefore difficult to parse. The Parse method attempts to parse astring with several implicit parse patterns, all of which might fail. The ParseExactmethod, in contrast, requires you to explicitly designate one or more exact parsepatterns that are likely to succeed.The following code example demonstrates the Parse method.Option ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim myDateTimeFrenchValue, myDateTimeFrench, culture, DateTimeStylesmyDateTimeFrenchValue = "16/02/1992 12:15:12"Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "fr-FR", True )Set DateTimeStyles = DotNetFactory.CreateInstance("System.Globalization.DateTimeStyles" )Set myDateTimeFrench = DotNetFactory.CreateInstance( "System.DateTime" ).Parse( _myDateTimeFrenchValue, culture, DateTimeStyles. NoCurrentDateDefault )MsgBox myDateTimeFrench.ToString()Set myDateTimeFrench = Nothing : Set culture = NothingSet DateTimeStyles = NothingDateTime.ParseExact MethodName DescriptionDateTime.ParseExact (String, Converts the specified string representation of a date
  • 66. Chapter 14 Scripting Quicktest Professional Page 66Dani Vainstein DotNetFactory Page 66 of 151String, IFormatProvider) and time to its DateTime equivalent using thespecified format and culture-specific formatinformation. The format of the string representationmust match the specified format exactly.DateTime.ParseExact (String,String, IFormatProvider,DateTimeStyles)Converts the specified string representation of a dateand time to its DateTime equivalent using thespecified format, culture-specific format information,and style. The format of the string representation mustmatch the specified format exactly.DateTime.ParseExact (String,String(), IFormatProvider,DateTimeStyles)Converts the specified string representation of a dateand time to its DateTime equivalent using thespecified array of formats, culture-specific formatinformation, and style. The format of the stringrepresentation must match at least one of thespecified formats exactly.DateTime.ParseExact ( String, String, IFormatProvider )MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified format and culture-specific format information. The formatof the string representation must match the specified format exactly.instance.ParseExact( s, format, provider )Parameter Descriptions A string containing a date and time to convert.format The expected format of s.providerAn IFormatProvider that supplies culture-specific format informationabout s.A DateTime equivalent to the date and time contained in s as specified by formatand provider.ArgumentNullException - s or format is a null reference (Nothing in Visual Basic).FormatException.s or format is an empty string.s does not contain a date and time that corresponds to the pattern specified informat.The s parameter contains the date and time to parse. If the s parameter containsonly a time and no date, the current date is used. If the s parameter contains only adate and no time, midnight (00:00:00) is used. The s parameter cannot containleading, inner, or trailing white space characters.The format parameter contains a pattern that corresponds to the expected format of
  • 67. Chapter 14 Scripting Quicktest Professional Page 67Dani Vainstein DotNetFactory Page 67 of 151the s parameter. The pattern in the format parameter consists of one or morecustom format specifiers from the Custom DateTime Format Strings table, or asingle standard format specifier, which identifies a predefined pattern, from theStandard DateTime Format Strings table.If you do not use date or time separators in a custom format pattern, use theinvariant culture for the provider parameter and the widest form of each customformat specifier. For example, if you want to specify hours in the pattern, specify thewider form, "HH", instead of the narrower form, "H".The provider parameter supplies culture-specific date and time formattinginformation, such as the names of the days of the week in a particular language, orthe preferred presentation order of the month, day, and year. The format parameteris typically a culture represented by a CultureInfo object. If provider is a nullreference (Nothing in Visual Basic), the current culture is used.The following code example demonstrates the ParseExact methodOption ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim dateToParse, culture, DateTimemyDateTimeFrenchValue = "11/02/2007 15:30:44"Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "en-GB", True )Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" ).ParseExact( _dateToParse, "G", culture )MsgBox DateTime.ToString()Set DateTime = Nothing : Set culture = NothingDateTime.ParseExact ( String, String, IFormatProvider,DateTimeStyles ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified format, culture-specific format information, and style. Theformat of the string representation must match the specified format exactlyinstance.ParseExact( s, format, provider, styles )Parameter Descriptions A string containing a date and time to convert.format The expected format of s.provider An IFormatProvider that supplies culture-specific format information
  • 68. Chapter 14 Scripting Quicktest Professional Page 68Dani Vainstein DotNetFactory Page 68 of 151about s.stylesA bitwise combination of DateTimeStyles values that indicates thepermitted format of s. A typical value to specify is None.A DateTime equivalent to the date and time contained in s as specified by format,provider, and style.ArgumentNullException - s or format is a null reference (Nothing in Visual Basic).FormatException.s or format is an empty string.s does not contain a date and time that corresponds to the pattern specified informat.ArgumentException - style contains an invalid combination of DateTimeStyles values.For example, both AssumeLocal and AssumeUniversal.The s parameter contains the date and time to parse. If the s parameter containsonly a time and no date, the current date is used. If the s parameter contains only adate and no time, midnight (00:00:00) is used. The s parameter cannot containleading, inner, or trailing white space characters.The format parameter contains a pattern that corresponds to the expected format ofthe s parameter. The pattern in the format parameter consists of one or morecustom format specifiers from the Custom DateTime Format Strings table, or asingle standard format specifier, which identifies a predefined pattern, from theStandard DateTime Format Strings table.If you do not use date or time separators in a custom format pattern, use theinvariant culture for the provider parameter and the widest form of each customformat specifier. For example, if you want to specify hours in the pattern, specify thewider form, "HH", instead of the narrower form, "H".The provider parameter supplies culture-specific date and time formattinginformation, such as the names of the days of the week in a particular language, orthe preferred presentation order of the month, day, and year. The format parameteris typically a culture represented by a CultureInfo object. If provider is a nullreference (Nothing in Visual Basic), the current culture is used.DateTime.ParseExact ( String, String[], IFormatProvider,DateTimeStyles ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified format, culture-specific format information, and style. Theformat of the string representation must match the specified format exactlyinstance.ParseExact( s, formats, provider, styles )Parameter Descriptions A string containing a date and time to convert.
  • 69. Chapter 14 Scripting Quicktest Professional Page 69Dani Vainstein DotNetFactory Page 69 of 151formats An array of expected formats of s.providerAn IFormatProvider that supplies culture-specific format informationabout s.stylesA bitwise combination of DateTimeStyles values that indicates thepermitted format of s. A typical value to specify is None.A DateTime equivalent to the date and time contained in s as specified by format,provider, and style.ArgumentNullException - s or format is a null reference (Nothing in Visual Basic).FormatException.s is an empty string.an element of formats is an empty string.s does not contain a date and time that corresponds to the pattern specified informats.ArgumentExceptionstyle contains an invalid combination of DateTimeStyles values.For example, both AssumeLocal and AssumeUniversal.The s parameter contains the date and time to parse. If the s parameter containsonly a time and no date, the current date is used. If the s parameter contains only adate and no time, midnight (00:00:00) is used. The s parameter cannot containleading, inner, or trailing white space characters.The format parameter contains a pattern that corresponds to the expected format ofthe s parameter. The pattern in the format parameter consists of one or morecustom format specifiers from the Custom DateTime Format Strings table, or asingle standard format specifier, which identifies a predefined pattern, from theStandard DateTime Format Strings table.If you do not use date or time separators in a custom format pattern, use theinvariant culture for the provider parameter and the widest form of each customformat specifier. For example, if you want to specify hours in the pattern, specify thewider form, "HH", instead of the narrower form, "H".The provider parameter supplies culture-specific date and time formattinginformation, such as the names of the days of the week in a particular language, orthe preferred presentation order of the month, day, and year. The format parameteris typically a culture represented by a CultureInfo object. If provider is a nullreference (Nothing in Visual Basic), the current culture is used.The following code example demonstrates the ParseExact methodOption ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim myDateTimeFrenchValueDim myDateTimeFrench, culture, DateTimeStyles, SystemArrayDim SystemType, expectedFormatsmyDateTimeFrenchValue = "16/02/1992 12:15:12"Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "fr-FR", True )
  • 70. Chapter 14 Scripting Quicktest Professional Page 70Dani Vainstein DotNetFactory Page 70 of 151Set DateTimeStyles = DotNetFactory.CreateInstance( _"System.Globalization.DateTimeStyles" ) ** Creating array of StringsSet SystemType = DotNetFactory.CreateInstance( "System.Type" )Set SystemArray = DotNetFactory.CreateInstance( "System.Array" )Set expectedFormats = SystemArray.CreateInstance( _SystemType.GetType( "System.String" ), 4 )expectedFormats.SetValue "G", 0 : expectedFormats.SetValue "g", 1expectedFormats.SetValue "f", 2 : expectedFormats.SetValue "F", 3Set myDateTimeFrench = DotNetFactory.CreateInstance( _"System.DateTime" ).ParseExact( _myDateTimeFrenchValue, _expectedFormats, _culture, _DateTimeStyles.NoCurrentDateDefault )MsgBox myDateTimeFrench.ToString()Set myDateTimeFrench = Nothing : Set culture = NothingSet DateTimeStyles = Nothing : Set expectedFormats = NothingSet SystemType = NothingDateTime.SpecifyKind ( DateTime, DateTimeKind ) MethodCreates a new DateTime object that represents the same time as the specifiedDateTime, but is designated in either local time, Coordinated Universal Time (UTC), orneither, as indicated by the specified DateTimeKind value.instance.DateTimeKind( value, kind )Parameter Descriptionvalue A DateTime object.kind One of the DateTimeKind values.A new DateTime object consisting of the same time represented by the valueparameter and the DateTimeKind value specified by the kind parameter.
  • 71. Chapter 14 Scripting Quicktest Professional Page 71Dani Vainstein DotNetFactory Page 71 of 151A DateTime object consists of a Kind field that indicates whether the time value isbased on local time, Coordinated Universal Time (UTC), or neither, and a Ticks fieldthat contains a time value measured in 100-nanosecond ticks. The SpecifyKindmethod creates a new DateTime object using the specified kind parameter and theoriginal time value.The SpecifyKind method is useful in interoperability scenarios where you receive aDateTime object with an unspecified Kind field, but you can determine byindependent means that the Ticks field represents local time or UTC.The following code example demonstrates the DateTimeKind method.See ExampleDateTime.Subtract MethodName DescriptionDateTime.Subtract (DateTime)Subtracts the specified date and time from thisinstance.DateTime.Subtract (TimeSpan) Subtracts the specified duration from this instance.DateTime.Subtract ( DateTime ) MethodAdds a specified time interval to a specified date and time, yielding a new date and time.Set timeSpan = instance.Subtract( value )Parameter Descriptionvalue An instance of DateTime.A TimeSpan interval equal to the date and time represented by this instance minusthe date and time represented by valueArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime object. Instead, a newTimeSpan is returned whose value is the result of this operation.Before subtracting DateTime objects, insure that the objects represent times in thesame time zone. Otherwise, the result will include the difference between timezones.The following code example demonstrates the addition operator.Option Explicit
  • 72. Chapter 14 Scripting Quicktest Professional Page 72Dani Vainstein DotNetFactory Page 72 of 151Dim date1, date2, date3, date4Dim diff1Set date1 = DotNetFactory.CreateInstance( "System.DateTime",,1996, 6, 3, 22, 15, 0 )Print "date1 - " & date1.ToString()Set date2 = DotNetFactory.CreateInstance( "System.DateTime",,1996, 12, 6, 13, 2, 0 )Print "date2 - " & date2.ToString()Set date3 = DotNetFactory.CreateInstance( "System.DateTime",,1996, 10, 12,8, 42, 0 )Print "date3 - " & date3.ToString() ** diff1 gets 185 days, 14 hours, and 47 minutes.Set diff1 = date2.Subtract( date1 )Print "diff1 - " & diff1.ToString() ** date4 gets 4/9/1996 5:55:00 PM.Set date4 = date3.Subtract( diff 1)Print "date4 - " & date4.ToString()Set date1 = Nothing : Set date2 = Nothing : Set date3 = NothingSet date4 = Nothing : Set diff1 = NothingDateTime.Subtract ( TimeSpan ) MethodSubtracts the specified duration from this instance.Set dateTime = instance.Subtract( value )Parameter Descriptionvalue An instance of TimeSpan.A DateTime equal to the date and time represented by this instance minus the timeinterval represented by value.ArgumentOutOfRangeException - The resulting DateTime is less than MinValue orgreater than MaxValue.This method does not change the value of this DateTime. Instead, a new DateTimeis returned whose value is the result of this operation
  • 73. Chapter 14 Scripting Quicktest Professional Page 73Dani Vainstein DotNetFactory Page 73 of 151DateTime.ToFileTime () MethodConverts 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.ArgumentOutOfRangeException - The resulting file time would represent a date andtime before 12:00 midnight January 1, 1601 C.E. UTC..A Windows file time is a 64-bit value that represents the number of 100-nanosecondintervals 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 anapplication creates, accesses, or writes to a file.Previous versions of the ToFileTime method assume the current DateTime objectis a local time. Starting with the.NET Framework version 2.0, the ToFileTimemethod uses the Kind property to determine whether the current DateTime objectis a local time, a UTC time, or an unspecified kind of time which is treated as a localtime.The following code example demonstrates the ToFileTime methodOption ExplicitDim filePath, FileDim fileCreationDateTime, fileCreationFileTimeDim oDialogSet oDialog = CreateObject( "UserAccounts.CommonDialog" )oDialog.Filter = "QTP Library Files|*.vbs;*.qfl|All Files|*.*"oDialog.FilterIndex = 1oDialog.InitialDir = Environment( "ProductDir" )If oDialog.ShowOpen = 0 ThenExitTest( 0 )ElsefilePath = oDialog.FileNameEnd IfSet File = DotNetFactory.CreateInstance( "System.IO.File" )If File.Exists( filePath ) ThenSet fileCreationDateTime = File.GetCreationTime(filePath)fileCreationFileTime = fileCreationDateTime.ToFileTime()Print fileCreationDateTime.ToString & " in file time is " & fileCreationFileTimeSet fileCreationDateTime = NothingElsePrint filePath & " is an invalid file"End IfSet File = Nothing
  • 74. Chapter 14 Scripting Quicktest Professional Page 74Dani Vainstein DotNetFactory Page 74 of 151DateTime.ToFileTimeUtc () MethodConverts the value of the current DateTime object to a Windows file time.Set DateTime = instance.ToFileTimeUtc()The value of the current DateTime object expressed as a Windows file time.ArgumentOutOfRangeException - The resulting file time would represent a date andtime before 12:00 midnight January 1, 1601 C.E. UTC..A Windows file time is a 64-bit value that represents the number of 100-nanosecondintervals 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 anapplication creates, accesses, or writes to a file.Prior versions of the ToFileTimeUtc method assume the current DateTime objectis a UTC time. Starting with the.NET Framework version 2.0, the ToFileTimeUtcmethod uses the Kind property to determine whether the current DateTime objectis a local time, a UTC time, or an unspecified kind of time which is treated as a UTCtime.DateTime.ToLocalTime () MethodConverts the value of the current DateTime object to local time.Set DateTime = instance.ToLocalTime()A DateTime object whose Kind property is Local, and whose value is the local timeequivalent to the value of the current DateTime object, or MaxValue if the convertedvalue is too large to be represented by a DateTime object, or MinValue if theconverted value is too small to be represented as a DateTime object.ArgumentOutOfRangeException - The resulting file time would represent a date andtime before 12:00 midnight January 1, 1601 C.E. UTC..
  • 75. Chapter 14 Scripting Quicktest Professional Page 75Dani Vainstein DotNetFactory Page 75 of 151The local time is equal to the UTC time plus the UTC offset. For more informationabout the UTC offset, see TimeZone.GetUtcOffset. The conversion also takes intoaccount the daylight saving time rule that applies to the time represented by thecurrent DateTime object.The following code example demonstrates the ToLocalTime method.Option ExplicitDim localDT, univDTDim sDateTimesDateTime = "02/13/2006 23:33:45"Set localDT = DotNetFactory.CreateInstance( "System.DateTime" ).Parse( sDateTime )Set univDT = localDT.ToUniversalTime()Print localDT & " local time is " & univDT & " universal time."sDateTime = "02/14/2006 12:33:45"Set univDT = DotNetFactory.CreateInstance( "System.DateTime" ).Parse( sDateTime )Set localDT = univDT.ToLocalTime()Print univDT & " universal time is " & localDT & " local time."Set localDT = Nothing : Set univDT = NothingDateTime.ToLongDateString () MethodConverts the value of the current DateTime object to its equivalent long datereturnValue = instance.ToLongDateString()A string that contains the long date string representation of the current DateTimeobject.ArgumentOutOfRangeException - The resulting file time would represent a date andtime before 12:00 midnight January 1, 1601 C.E. UTC..The value of the current DateTime object is formatted using the long date formatcharacter, D. The long date format character represents the pattern defined by theLongDatePattern property associated with the current thread culture. The returnvalue is identical to the value returned by specifying the "D" standard DateTimeformat string with the ToString(String) method.For more information about the current thread culture, see the CurrentCultureproperty. For more information about format characters, format patterns, and theoutput they produce, see the Formatting Overview topic. For more information about
  • 76. Chapter 14 Scripting Quicktest Professional Page 76Dani Vainstein DotNetFactory Page 76 of 151changing the format pattern associated with a format character, see theDateTimeFormatInfo class.The following code example demonstrates the ToLongDateString method.Option ExplicitDim msg1Dim myDateTime, ci, sbmsg1 = _"The date and time patterns are defined in the DateTimeFormatInfo " & vbCrLf & _"object associated with the current appliation culture." & vbCrLf ** Initialize a DateTime object.Print "Initialize the DateTime object to May 16, 2001 3:02:15 AM." & vbCrLfSet myDateTime = DotNetFactory.CreateInstance( _"System.DateTime",,2001, 5, 16, 3, 2, 15 ) ** Identify the source of the date and time patterns.Print msg1 ** Display the name of the current culture.Set sb = DotNetFactory.CreateInstance( "System.Text.StringBuilder" )Set ci = DotNetFactory.CreateInstance( _"System.Windows.Forms.Application" ).CurrentCulture()sb.AppendFormat "Current culture: {0}{1}{0}" & vbCrLf, Chr(34), ci.Name ** Display the long date pattern and string.sb.AppendFormat "Long date pattern: {0}{1}{0}" & vbCrLf, _Chr(34), ci.DateTimeFormat.LongDatePatternsb.AppendFormat "Long date string: {0}{1}{0}", _Chr(34), myDateTime.ToLongDateString()sb.Append vbCrLf ** Display the long time pattern and string.sb.AppendFormat "Long time pattern: {0}{1}{0}" & vbCrLf, _Chr(34), ci.DateTimeFormat.LongTimePatternsb.AppendFormat "Long time string: {0}{1}{0}", _Chr(34), myDateTime.ToLongTimeString()sb.Append vbCrLf ** Display the short date pattern and string.sb.AppendFormat "Short date pattern: {0}{1}{0}" & vbCrLf, _Chr(34), ci.DateTimeFormat.ShortDatePatternsb.AppendFormat "Short date string: {0}{1}{0}", _Chr(34), myDateTime.ToShortDateString()sb.Append vbCrLf ** Display the short time pattern and string.sb.AppendFormat "Short time pattern: {0}{1}{0}" & vbCrLf, _Chr(34), ci.DateTimeFormat.ShortTimePatternsb.AppendFormat "Short time string: {0}{1}{0}" & vbCrLf, _Chr(34), myDateTime.ToShortTimeString()Print sb.ToString()Set myDateTime = Nothing : Set ci = Nothing : Set sb = Nothing
  • 77. Chapter 14 Scripting Quicktest Professional Page 77Dani Vainstein DotNetFactory Page 77 of 151DateTime.ToLongTimeString () MethodConverts the value of the current DateTime object to its equivalent long time stringrepresentation.returnValue = instance.ToLongTimeString()A string that contains the long time string representation of the current DateTimeobject.The value of the current DateTime object is formatted using the long date formatcharacter, D. The long date format character represents the pattern defined by theLongDatePattern property associated with the current thread culture. The returnvalue is identical to the value returned by specifying the "D" standard DateTimeformat string with the ToString(String) method.For more information about the current thread culture, see the CurrentCultureproperty. For more information about format characters, format patterns, and theoutput they produce, see the Formatting Overview topic. For more information aboutchanging the format pattern associated with a format character, see theDateTimeFormatInfo class.The following code example demonstrates the ToLongTimeString method.see ExampleDateTime.ToShortDateString () MethodConverts the value of the current DateTime object to its equivalent short date stringrepresentation.
  • 78. Chapter 14 Scripting Quicktest Professional Page 78Dani Vainstein DotNetFactory Page 78 of 151returnValue = instance.ToShortDateString()A string that contains the short date string representation of the current DateTimeobject.The value of the current DateTime object is formatted using the long date formatcharacter, D. The long date format character represents the pattern defined by theLongDatePattern property associated with the current thread culture. The returnvalue is identical to the value returned by specifying the "D" standard DateTimeformat string with the ToString(String) method.For more information about the current thread culture, see the CurrentCultureproperty. For more information about format characters, format patterns, and theoutput they produce, see the Formatting Overview topic. For more information aboutchanging the format pattern associated with a format character, see theDateTimeFormatInfo class.The following code example demonstrates the ToLongTimeString method.see ExampleDateTime.ToShortTimeString () MethodConverts the value of the current DateTime object to its equivalent short time stringrepresentation.returnValue = instance.ToShortTimeString()A string that contains the long time string representation of the current DateTimeobject.The value of the current DateTime object is formatted using the long date formatcharacter, D. The long date format character represents the pattern defined by theLongDatePattern property associated with the current thread culture. The returnvalue is identical to the value returned by specifying the "D" standard DateTimeformat string with the ToString(String) method.For more information about the current thread culture, see the CurrentCultureproperty. For more information about format characters, format patterns, and theoutput they produce, see the Formatting Overview topic. For more information aboutchanging the format pattern associated with a format character, see theDateTimeFormatInfo class.The following code example demonstrates the ToShortTimeString method.see Example
  • 79. Chapter 14 Scripting Quicktest Professional Page 79Dani Vainstein DotNetFactory Page 79 of 151DateTime.ToString MethodName DescriptionDateTime.ToString ()Converts the value of the current DateTime object toits equivalent string representation.DateTime.ToString(IFormatProvider)Converts the value of the current DateTime object toits equivalent string representation using the specifiedculture-specific format information.DateTime.ToString (String)Converts the value of the current DateTime object toits equivalent string representation using the specifiedformat.DateTime.ToString (String,IFormatProvider)Converts the value of the current DateTime object toits equivalent string representation using the specifiedformat and culture-specific format information.DateTime.ToString () MethodConverts the value of the current DateTime object to its equivalent stringrepresentation.returnValue = instance.ToString()A string representation of the value of the current DateTime object.The value of the current DateTime object is formatted using the general date andtime format specifier (G).The .NET Framework provides extensive formatting support, which is described ingreater detail in the following formatting topics:For more information about date and time format specifiers, see StandardDateTime Format Strings and Custom DateTime Format Strings.For more information about formatting, see Formatting Types and FormattingOverview.This method uses formatting information derived from the current culture. For moreinformation, see CurrentCulture.The following code example demonstrates the ToString method.Option ExplicitDim msgDim thisDate, utcDate, unspecifiedDate, ci, dtkSet msg = CreateObject( "Scripting.Dictionary" )msg.Add "MSG_SHORT_DATE", "(d) Short date --> "msg.Add "MSG_LONG_DATE", "(D) Long date --> "msg.Add "MSG_SHORT_TIME", "(t) Short time --> "msg.Add "MSG_LONG_TIME", "(T) Long time --> "
  • 80. Chapter 14 Scripting Quicktest Professional Page 80Dani Vainstein DotNetFactory Page 80 of 151msg.Add "MSG_FULLSHORT_TIME", "(f) Full date/short time --> "msg.Add "MSG_FULLLONG_TIME", "(F) Full date/long time --> "msg.Add "MSG_GENSHORT_TIME", "(g) General date/short time --> "msg.Add "MSG_GENLONG_TIME", "(G) General date/long time (default) --> "msg.Add "MSG_MONTH", "(M) Month --> "msg.Add "MSG_RFC1123", "(R) RFC1123 --> "msg.Add "MSG_SORT", "(s) Sortable --> "msg.Add "MSG_UNISOR_VAR", "(u) Universal sortable (invariant) --> "msg.Add "MSG_UNISORT", "(U) Universal sortable --> "msg.Add "MSG_YEAR", "(Y) Year --> "msg.Add "MSG_ROUNDTRIP_LOC", "(o) Roundtrip (local) --> "msg.Add "MSG_ROUNDTRIP_UTC", "(o) Roundtrip (UTC) --> "msg.Add "MSG_ROUNDTRIP_UNS", "(o) Roundtrip (Unspecified) --> "msg.Add "MSG1", "Using ToString( String ) and the current thread culture." & vbCrLfmsg.Add "MSG2", "Using ToString( String, IFormatProvider ) " & _" and a specified culture." & vbCrLfmsg.Add "MSG_THIS_DATE", "This date and time --> "Set dtk = DotNetFactory.CreateInstance( "System.DateTimeKind" )Set thisDate = DotNetFactory.CreateInstance( "System.DateTime" ).Now()Set utcDate = DotNetFactory.CreateInstance( "System.DateTime" ).ToUniversalTime()Set unspecifiedDate = DotNetFactory.CreateInstance( _"System.DateTime", ,2000, 3, 20, 13, 2, 3, 0, dtk.Unspecified ) ** Format the current date and time in various ways.Print "Standard DateTime Format Specifiers:" & vbCrLfPrint msg( "MSG_THIS_DATE" ) & thisDate.ToString() & vbCrLfPrint msg( "MSG1" ) ** Display the thread current culture, which is used to format the values.Set ci = DotNetFactory.CreateInstance( _"System.Windows.Forms.Application" ).CurrentCulture()Print "Culture --> " & ci.DisplayNamePrint 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.
  • 81. Chapter 14 Scripting Quicktest Professional Page 81Dani Vainstein DotNetFactory Page 81 of 151Print msg( "MSG2" ) ** Display the culture used to format the values.Set ci = DotNetFactory.CreateInstance( _"System.Globalization.CultureInfo",, "de-DE" )Print "Culture --> " & ci.DisplayNamePrint msg( "MSG_SHORT_DATE" ) & thisDate.ToString( "d", ci )Print msg( "MSG_LONG_DATE" ) & thisDate.ToString( "D", ci )Print msg( "MSG_SHORT_TIME" ) & thisDate.ToString( "t", ci )Print msg( "MSG_LONG_TIME" ) & thisDate.ToString( "T", ci )Print msg( "MSG_FULLSHORT_TIME" ) & thisDate.ToString( "f", ci )Print msg( "MSG_FULLLONG_TIME" ) & thisDate.ToString( "F", ci )Print msg( "MSG_GENSHORT_TIME" ) & thisDate.ToString( "g", ci )Print msg( "MSG_GENLONG_TIME" ) & thisDate.ToString( "G", ci )Print msg( "MSG_MONTH" ) & thisDate.ToString( "M", ci )Print msg( "MSG_RFC1123" ) & utcDate.ToString( "R", ci )Print msg( "MSG_SORT" ) & thisDate.ToString( "s", ci )Print msg( "MSG_UNISOR_VAR" ) & utcDate.ToString( "u", ci )Print msg( "MSG_UNISORT" ) & thisDate.ToString( "U", ci )Print msg( "MSG_YEAR" ) & thisDate.ToString( "Y", ci )Print msg( "MSG_ROUNDTRIP_LOC" ) & thisDate.ToString( "o", ci )Print msg( "MSG_ROUNDTRIP_UTC" ) & utcDate.ToString( "o", ci )Print msg( "MSG_ROUNDTRIP_UNS" ) & unspecifiedDate.ToString( "o", ci )Print String( 50, "=" ) & vbCrLfSet dtk = Nothing : Set msg = NothingSet thisDate = Nothing : Set utcDate = Nothing : Set unspecifiedDate = Nothing
  • 82. Chapter 14 Scripting Quicktest Professional Page 82Dani Vainstein DotNetFactory Page 82 of 151DateTime.ToString ( IFormatProvider ) MethodConverts the value of the current DateTime object to its equivalent stringrepresentation using the specified culture-specific format information.
  • 83. Chapter 14 Scripting Quicktest Professional Page 83Dani Vainstein DotNetFactory Page 83 of 151returnValue = instance.ToString( provider )Parameter Descriptionprovider An IFormatProvider that supplies culture-specific formatting information.A string representation of value of the current DateTime object as specified byprovider..The value of the current DateTime object is formatted using the general date andtime format specifier (G).The .NET Framework provides extensive formatting support, which is described ingreater detail in the following formatting topics:For more information about date and time format specifiers, see StandardDateTime Format Strings and Custom DateTime Format Strings.For more information about formatting, see Formatting Types and FormattingOverview.This method uses formatting information derived from the current culture. For moreinformation, see CurrentCulture.The following code example demonstrates the ToString method.see Example ToStringDateTime.ToString ( String ) MethodConverts the value of the current DateTime object to its equivalent stringrepresentation using the specified format.returnValue = instance.ToString( format )Parameter Descriptionformat A DateTime format string.A string representation of value of the current DateTime object as specified byformat.FormatExceptionThe length of format is 1, and it is not one of the format specifier charactersdefined for DateTimeFormatInfo.format does not contain a valid custom format pattern.
  • 84. Chapter 14 Scripting Quicktest Professional Page 84Dani Vainstein DotNetFactory Page 84 of 151The format parameter should contain either a format specifier character or a customformat pattern. For more information, see the summary page forSystem.Globalization.DateTimeFormatInfo.If format is a null reference (Nothing in Visual Basic) or an empty string, the generalformat specifier, G, is used.The .NET Framework provides extensive formatting support, which is described ingreater detail in the following formatting topics:For more information about date and time format specifiers, see StandardDateTime Format Strings and Custom DateTime Format Strings.For more information about formatting, see Formatting Types and FormattingOverview.The following code example demonstrates the ToString method.see also Example ToStringOption ExplicitDim DateTimeSet DateTime = DotNetFactory.CreateInstance( "System.DateTime" ).Now()Print "%d --> " & DateTime.ToString( "%d" )Print "dd --> " & DateTime.ToString( "dd" )Print "ddd --> " & DateTime.ToString( "ddd" )Print "dddd --> " & DateTime.ToString( "dddd" )Print "ddd, d --> " & DateTime.ToString( "ddd, d" )Print "ff --> " & DateTime.ToString( "ff" )Print "fff --> " & DateTime.ToString( "fff" )Print "fffff --> " & DateTime.ToString( "fffff" )Print "gg --> " & DateTime.ToString( "gg" )Print "hh --> " & DateTime.ToString( "hh" )Print "HH --> " & DateTime.ToString( "HH" )Print "MM --> " & DateTime.ToString( "MM" )Print "MMM --> " & DateTime.ToString( "MMM" )Print "MMMM --> " & DateTime.ToString( "MMMM" )Print "tt --> " & DateTime.ToString( "tt" )Print "yy --> " & DateTime.ToString( "yy" )Print "yyyy --> " & DateTime.ToString( "yyyy" )Print "zz --> " & DateTime.ToString( "zz" )Print "zzz --> " & DateTime.ToString( "zzz" )Print "%h --> " & DateTime.ToString( "%h" )Print "yyyy %g --> " & DateTime.ToString( "yyyy %g" )Print "d, ddd MMM yyyy K --> " & DateTime.ToString( "d, dddd MMM yyyy K" )Print "Log_" & DateTime.ToString( "ddMMyyyy_HHmmss" ) & ".txt"Print "Log_" & DateTime.ToString( "ddMMyyyy_hmmsstt" ) & ".txt"Set DateTime = Nothing
  • 85. Chapter 14 Scripting Quicktest Professional Page 85Dani Vainstein DotNetFactory Page 85 of 151DateTime.ToString ( String, IFormatProvider ) MethodConverts the value of the current DateTime object to its equivalent stringrepresentation using the specified format and culture-specific format information.returnValue = instance.ToString( format, provider )Parameter Descriptionformat A DateTime format string.provider An IFormatProvider that supplies culture-specific formatting information.A string representation of value of the current DateTime object as specified byformat and providerExceptionFormat ExceptionThe length of format is 1, and it is not one of the format specifier charactersdefined for DateTimeFormatInfo.format does not contain a valid custom format pattern.
  • 86. Chapter 14 Scripting Quicktest Professional Page 86Dani Vainstein DotNetFactory Page 86 of 151The format parameter should contain either a format specifier character or a customformat pattern. For more information, see the summary page forSystem.Globalization.DateTimeFormatInfo.If format is a null reference (Nothing in Visual Basic) or an empty string, the generalformat specifier, G, is used.The .NET Framework provides extensive formatting support, which is described ingreater detail in the following formatting topics:For more information about date and time format specifiers, see StandardDateTime Format Strings and Custom DateTime Format Strings.For more information about formatting, see Formatting Types and FormattingOverview.The following code example demonstrates the ToString method.see Example ToStringDateTime.ToUniversalTime () MethodConverts 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 UTCequivalent to the value of the current DateTime object, or MaxValue if the convertedvalue is too large to be represented by a DateTime object, or MinValue if theconverted 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 informationabout the UTC offset, see TimeZone.GetUtcOffset. The conversion also takes intoaccount the daylight saving time rule that applies to the time represented by thecurrent DateTime object.The value returned by this conversion is a DateTime object whose Kind property isUtc. Consequently, a valid result is returned even if ToUniversalTime is appliedrepeatedly to the same DateTime object.This method always uses the local time zone when making calculations.DateTime.TryParse MethodName DescriptionDateTime.TryParse (String,DateTime)Converts the specified string representation of a dateand time to its DateTime equivalent.DateTime.TryParse (String,IFormatProvider, DateTimeStyles,DateTime)Converts the specified string representation of a dateand time to its DateTime equivalent using thespecified culture-specific format information andformatting style.
  • 87. Chapter 14 Scripting Quicktest Professional Page 87Dani Vainstein DotNetFactory Page 87 of 151DateTime.TryParse ( String, DateTime ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent.returnValue = instance.TryParse( s, result )Parameter Descriptions A string containing a date and time to convert.resultWhen this method returns, contains the DateTime value equivalent tothe date and time contained in s, if the conversion succeeded, orMinValue if the conversion failed. The conversion fails if the s parameteris a null reference (Nothing in Visual Basic), or does not contain a validstring representation of a date and time. This parameter is passeduninitialized.true if the s parameter was converted successfully; otherwise, false.The TryParse method is similar to the Parse method, except that the TryParsemethod does not throw an exception if the conversion fails.The string s is parsed using formatting information in the currentDateTimeFormatInfo object, which is supplied implicitly by the current threadculture.This method attempts to ignore unrecognized data and parse s completely. Itignores unrecognized data if possible and fills in missing month, day, and yearinformation with the current time. If s contains only a date and no time, this methodassumes the time is 12:00 midnight. Any leading, inner, or trailing white spacecharacter in s is ignored. The date and time can be bracketed with a pair of leadingand trailing NUMBER SIGN characters (#, U+0023), and can be trailed with one ormore NULL characters (U+0000).The s parameter must contain the representation of a date and time in one of theformats described in the DateTimeFormatInfo class.Notes to Callers: Formatting is influenced by properties of the currentDateTimeFormatInfo object, which by default are derived from the Regional andLanguage Options item in Control Panel. One reason the TryParse method canunexpectedly throw FormatException is if the currentDateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparatorproperties are set to the same value.The following code example demonstrates the TryParse method.Option ExplicitDim DateTime, myDateTimeDim myDateTimeValuemyDateTimeValue = "2/16/1992 12:15:12"
  • 88. Chapter 14 Scripting Quicktest Professional Page 88Dani Vainstein DotNetFactory Page 88 of 151Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" )Set myDateTime = DotNetFactory.CreateInstance( "System.DateTime" )If DateTime.TryParse( myDateTimeValue, myDateTime ) ThenMsgBox myDateTime.ToString()End IfSet DateTime = Nothing : Set myDateTime = NothingDateTime.TryParse ( String, IFormatProvider,DateTimeStyles, DateTime ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified culture-specific format information and formatting style.returnValue = instance.TryParse( s, provider, styles, result )Parameter Descriptions A string containing a date and time to convert.resultAn IFormatProvider object that supplies culture-specific formattinginformation about s.stylesA bitwise combination of DateTimeStyles values that indicates thepermitted format of s. A typical value to specify is None.resultWhen this method returns, contains the DateTime value equivalent tothe date and time contained in s, if the conversion succeeded, orMinValue if the conversion failed. The conversion fails if the s parameteris a null reference (Nothing in Visual Basic), or does not contain a validstring representation of a date and time. This parameter is passeduninitialized.true if the s parameter was converted successfully; otherwise, false.ArgumentExceptionIf format is a null reference (Nothing in Visual Basic) or an empty string, the generalformat specifier, G, is used.The .NET Framework provides extensive formatting support, which is described ingreater 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 ).
  • 89. Chapter 14 Scripting Quicktest Professional Page 89Dani Vainstein DotNetFactory Page 89 of 151The TryParse method is similar to the Parse method, except that the TryParsemethod does not throw an exception if the conversion fails.The string s is parsed using formatting information in the currentDateTimeFormatInfo object, which is supplied implicitly by the current threadculture.This method attempts to ignore unrecognized data and parse s completely. Itignores unrecognized data if possible and fills in missing month, day, and yearinformation with the current time. If s contains only a date and no time, this methodassumes the time is 12:00 midnight. Any leading, inner, or trailing white spacecharacter in s is ignored. The date and time can be bracketed with a pair of leadingand trailing NUMBER SIGN characters (#, U+0023), and can be trailed with one ormore NULL characters (U+0000).The s parameter must contain the representation of a date and time in one of theformats described in the DateTimeFormatInfo class.The provider parameter supplies culture-specific date and time formattinginformation. For example, it might supply the names of the days of the week in aparticular language, or the preferred order of presentation for the month, day, andyear. If provider is a null reference (Nothing in Visual Basic), the current culture isused.Notes to Callers: Formatting is influenced by properties of the currentDateTimeFormatInfo object, which by default are derived from the Regional andLanguage Options item in Control Panel. One reason the TryParse method canunexpectedly throw FormatException is if the currentDateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparatorproperties are set to the same value.DateTime.TryParseExact MethodName DescriptionDateTime.TryParseExact Method(String, String, IFormatProvider,DateTimeStyles, DateTime)Converts the specified string representation of a dateand time to its DateTime equivalent using the specifiedformat, culture-specific format information, and style.The format of the string representation must matchthe specified format exactly.DateTime.TryParseExact (String,String[], IFormatProvider,DateTimeStyles, DateTime)Converts the specified string representation of a dateand time to its DateTime equivalent using the specifiedarray of formats, culture-specific format information,and style. The format of the string representation mustmatch at least one of the specified formats exactlyDateTime.TryParse ( String, String, IFormatProvider,DateTimeStyles, DateTime ) MethodConverts the specified string representation of a date and time to its DateTimeequivalent using the specified format, culture-specific format information, and style. Theformat of the string representation must match the specified format exactly.returnValue = instance.TryParseExact( s, format, provider, styles, result )
  • 90. Chapter 14 Scripting Quicktest Professional Page 90Dani Vainstein DotNetFactory Page 90 of 151Parameter Descriptions A string containing a date and time to convert.format The expected format of s.providerAn IFormatProvider object that supplies culture-specific formattinginformation about s.stylebitwise combination of one or more DateTimeStyles values that indicatethe permitted format of s.resultWhen this method returns, contains the DateTime value equivalent tothe date and time contained in s, if the conversion succeeded, orMinValue if the conversion failed. The conversion fails if the s parameteris a null reference (Nothing in Visual Basic), or does not contain a validstring representation of a date and time. This parameter is passeduninitialized.true if the s parameter was converted successfully; otherwise, false.ArgumentExceptionstyles 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 theTryParseExact method does not throw an exception if the conversion fails.The s parameter contains the date and time to parse. If the s parameter containsonly a time and no date, the style parameter determines whether the current dateor 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 sparameter can contain leading, inner, or trailing white space charactersThe format parameter contains a pattern that corresponds to the expected formatof the s parameter. The pattern in the format parameter consists of one or morecustom format specifiers from the Custom DateTime Format Strings table, or asingle standard format specifier, which identifies a predefined pattern, from theStandard DateTime Format Strings table.If you do not use date or time separators in a custom format pattern, use theinvariant culture for the provider parameter and the widest form of each customformat specifier. For example, if you want to specify hours in the pattern, specify thewider form, "HH", instead of the narrower form, "H".The provider parameter supplies culture-specific date and time formattinginformation, such as the names of the days of the week in a particular language, orthe preferred presentation order of the month, day, and year. The formatparameter is typically a culture represented by a CultureInfo object. If provider is anull reference (Nothing in Visual Basic), the current culture is used.DateTime.TryParse ( String, String[], IFormatProvider,DateTimeStyles, DateTime ) Method
  • 91. Chapter 14 Scripting Quicktest Professional Page 91Dani Vainstein DotNetFactory Page 91 of 151Converts the specified string representation of a date and time to its DateTimeequivalent using the specified format, culture-specific format information, and style. Theformat of the string representation must match the specified format exactly.returnValue = instance.TryParseExact( s, format, provider, styles, result )Parameter Descriptions A string containing a date and time to convert.formats An array of expected formats of s.providerAn IFormatProvider object that supplies culture-specific formattinginformation about s.stylebitwise combination of one or more DateTimeStyles values that indicatethe permitted format of s.resultWhen this method returns, contains the DateTime value equivalent tothe date and time contained in s, if the conversion succeeded, orMinValue if the conversion failed. The conversion fails if the s parameteris a null reference (Nothing in Visual Basic), or does not contain a validstring representation of a date and time. This parameter is passeduninitialized.true if the s parameter was converted successfully; otherwise, false.ArgumentExceptionstyles 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 theTryParseExact method does not throw an exception if the conversion fails.The s parameter contains the date and time to parse. If the s parameter containsonly a time and no date, the style parameter determines whether the current dateor 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 sparameter can contain leading, inner, or trailing white space charactersThe format parameter contains a pattern that corresponds to the expected formatof the s parameter. The pattern in the format parameter consists of one or morecustom format specifiers from the Custom DateTime Format Strings table, or asingle standard format specifier, which identifies a predefined pattern, from theStandard DateTime Format Strings table.If you do not use date or time separators in a custom format pattern, use theinvariant culture for the provider parameter and the widest form of each customformat specifier. For example, if you want to specify hours in the pattern, specify thewider form, "HH", instead of the narrower form, "H".The provider parameter supplies culture-specific date and time formattinginformation, such as the names of the days of the week in a particular language, orthe preferred presentation order of the month, day, and year. The format
  • 92. Chapter 14 Scripting Quicktest Professional Page 92Dani Vainstein DotNetFactory Page 92 of 151parameter is typically a culture represented by a CultureInfo object. If provider is anull reference (Nothing in Visual Basic), the current culture is used.System.TimeSpan StructureA TimeSpan object represents a time interval, or duration of time, measured as a positiveor negative number of days, hours, minutes, seconds, and fractions of a second. The largestunit of time used to measure duration is a day. Time intervals are measured in days forconsistency because the number of days in larger units of time, such as months and years,varies.The value of a TimeSpan object is the number of ticks that equal the represented timeinterval. A tick is equal to 100 nanoseconds, and the value of a TimeSpan object can rangefrom MinValue to MaxValue.A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus signindicates a negative time interval, the d component is days, hh is hours as measured on a24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. That is, a timeinterval consists of a positive or negative number of days without a time of day, or anumber of days with a time of day, or only a time of day. For example, the textrepresentation of a TimeSpan object initialized to 1.0e+13 ticks is "11.13:46:40", whichmeans 11 days, 13 hours, 46 minutes, and 40 seconds.For more information see :http://msdn2.microsoft.com/en-us/library/system.timespan.aspxSystem.TimeSpan ContructorsInitializes a new TimeSpan.Name DescriptionTimeSpan (Int64)Initializes a new TimeSpan to the specified numberof ticks.TimeSpan (Int32, Int32, Int32)Initializes a new TimeSpan to a specified number ofhours, minutes, and seconds.TimeSpan (Int32, Int32, Int32,Int32)Initializes a new TimeSpan to a specified number ofdays, hours, minutes, and seconds.TimeSpan (Int32, Int32, Int32,Int32, Int32)Initializes a new TimeSpan to a specified number ofdays, hours, minutes, seconds, and milliseconds.DateTime.TimeSpan ( int64 ) ConstructorInitializes a new TimeSpan to the specified number of ticks.Set object =DotNetFactory.CreateInstance( "System.TimeSpan", , ticks )Parameter Description
  • 93. Chapter 14 Scripting Quicktest Professional Page 93Dani Vainstein DotNetFactory Page 93 of 151ticks A time period expressed in 100-nanosecond units.System.TimeSpan objectArgumentOutOfRangeException - ticks is less than MinValue or greater thanMaxValue.ArgumentException - Kind is not one of the DateTimeKind values.The following code example creates several TimeSpan objects using the constructoroverload that initializes a TimeSpan to a specified number of ticks.Option ExplicitDim int64 ** Create a TimeSpan object and display its value.Sub CreateTimeSpan( ByRef ticks )Dim ctor, elapsedStrDim pointIndex, elapsedTimeSet elapsedTime = DotNetFactory.CreateInstance( "System.TimeSpan",, ticks ) ** Format the constructor for display.ctor = "TimeSpan( " & ticks & " )" ** Pad the end of a TimeSpan string with spaces if it does not contain milliseconds.elapsedStr = elapsedTime.ToString( )pointIndex = Instr( 1, elapsedStr, ":" )pointIndex = Instr( pointIndex, elapsedStr, "." )If pointIndex < 0 Then elapsedStr = " " ** Display the constructor and its value.Print ctor & " ---> " & elapsedStrEnd SubPrint "This example of the TimeSpan( Long ) constructor " & _vbCrLf & "generates the following output." & vbCrLfCreateTimeSpan( 1 )CreateTimeSpan( 999999 ) ** Beacause vbScript cannot handle numbers greater then Long.MaxValueSet int64 = DotNetFactory.CreateInstance( "System.Int64" ).Parse( "-1000000000000" )CreateTimeSpan( int64 )Set int64 = DotNetFactory.CreateInstance( "System.Int64" ).Parse( "18012202000000" )CreateTimeSpan( int64 )Set int64 = DotNetFactory.CreateInstance( _"System.Int64" ).Parse( "999999999999999999" )CreateTimeSpan( int64 )Set int64 = DotNetFactory.CreateInstance( "System.Int64" ).Parse( "18012202000000" )CreateTimeSpan( int64 )Set int64 = Nothing
  • 94. Chapter 14 Scripting Quicktest Professional Page 94Dani Vainstein DotNetFactory Page 94 of 151DateTime.TimeSpan ( int32, int32, int32 ) ConstructorInitializes a new TimeSpan to a specified number of hours, minutes, and seconds.Set object =DotNetFactory.CreateInstance( "System.TimeSpan", , hours, minutes,seconds )Parameter Descriptionhours Number of hours.minutes Number of minutes.seconds Number of seconds.System.TimeSpan objectArgumentOutOfRangeException - The parameters specify a TimeSpan value lessthan than MinValue or greater than MaxValue.The specified hours, minutes, and seconds are converted to ticks, and that valueinitializes this instance.The following code example creates several TimeSpan objects using the constructoroverload that initializes a TimeSpan to a specified number of hours, minutes, andseconds.Option Explicit ** Create a TimeSpan object and display its value.Sub CreateTimeSpan( ByVal hours, ByVal minutes, ByVal seconds )Dim ctor, sbDim elapsedTimeSet elapsedTime = DotNetFactory.CreateInstance( _
  • 95. Chapter 14 Scripting Quicktest Professional Page 95Dani Vainstein DotNetFactory Page 95 of 151"System.TimeSpan",, hours, minutes, seconds )Set sb = DotNetFactory.CreateInstance( "System.Text.StringBuilder" ) ** Format the constructor for display.ctor = sb.AppendFormat( "TimeSpan( {0}, {1}, {2} )", _hours, minutes, seconds ).ToString ** Display the constructor and its value.Print ctor & " ---> " & elapsedTime.ToString()Set sb = NothingEnd SubPrint "This example of the TimeSpan( Integer, Integer, Integer ) constructor " & _vbCrLf & "generates the following output." & vbCrLfCall 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 )DateTime.TimeSpan ( int32, int32, int32, int32 )ConstructorInitializes a new TimeSpan to a specified number of days, hours, minutes, and seconds.Set object =DotNetFactory.CreateInstance( "System.TimeSpan", , days, hours, minutes,seconds )Parameter Descriptiondays Number of days.hours Number of hours.minutes Number of minutes.seconds Number of seconds.
  • 96. Chapter 14 Scripting Quicktest Professional Page 96Dani Vainstein DotNetFactory Page 96 of 151System.TimeSpan objectArgumentOutOfRangeException - The parameters specify a TimeSpan value lessthan than MinValue or greater than MaxValue.The specified days, hours, minutes, and seconds are converted to ticks, and thatvalue initializes this instance.The following code example creates several TimeSpan objects using the constructoroverload 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, sbDim elapsedTimeSet elapsedTime = DotNetFactory.CreateInstance( _"System.TimeSpan",, days, hours, minutes, seconds )Set sb = DotNetFactory.CreateInstance( "System.Text.StringBuilder" ) ** Format the constructor for display.ctor = sb.AppendFormat( "TimeSpan( {0}, {1}, {2} {3} )", _days, hours, minutes, seconds ).ToString ** Display the constructor and its value.Print ctor & " ---> " & elapsedTime.ToString()Set sb = NothingEnd SubPrint "This example of the TimeSpan " & _" ( Integer, Integer, Integer, Integer ) constructor " & _vbCrLf & "generates the following output." & vbCrLfCall CreateTimeSpan( 10, 20, 30, 40 )Call CreateTimeSpan( -10, 20, 30, 40 )Call CreateTimeSpan( 0, 0, 0, 937840 )Call CreateTimeSpan( 1000, 2000, 3000, 4000 )Call CreateTimeSpan( 1000, -2000, -3000, -4000 )Call CreateTimeSpan( 999999, 999999, 999999, 999999 )DateTime.TimeSpan ( int32, int32, int32, int32, int32 )ConstructorInitializes a new TimeSpan to a specified number of days, hours, minutes, seconds, andmilliseconds.
  • 97. Chapter 14 Scripting Quicktest Professional Page 97Dani Vainstein DotNetFactory Page 97 of 151Set object =DotNetFactory.CreateInstance( "System.TimeSpan", , days, hours, minutes,seconds, milliseconds )Parameter Descriptiondays Number of days.hours Number of hours.minutes Number of minutes.seconds Number of seconds.milliseconds Number of millisecondsSystem.TimeSpan objectArgumentOutOfRangeException - The parameters specify a TimeSpan value less thanthan MinValue or greater than MaxValue.The specified days, hours, minutes, seconds, and milliseconds are converted toticks, and that value initializes this instance.The following code example creates several TimeSpan objects using the constructoroverload 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, sbDim elapsedTimeSet elapsedTime = DotNetFactory.CreateInstance( _"System.TimeSpan",, days, hours, minutes, seconds )Set sb = DotNetFactory.CreateInstance( "System.Text.StringBuilder" ) ** Format the constructor for display.ctor = sb.AppendFormat( "TimeSpan( {0}, {1}, {2} {3} {4} )", _days, hours, minutes, seconds, milliseconds ).ToString ** Display the constructor and its value.Print ctor & " ---> " & elapsedTime.ToString()Set sb = NothingEnd SubPrint "This example of the TimeSpan " & _" ( Integer, Integer, Integer, Integer, Integer ) constructor " & _vbCrLf & "generates the following output." & vbCrLfCall CreateTimeSpan( 10, 20, 30, 40, 50 )Call CreateTimeSpan( -10, 20, 30, 40, 50 )
  • 98. Chapter 14 Scripting Quicktest Professional Page 98Dani Vainstein DotNetFactory Page 98 of 151Call CreateTimeSpan( 0, 0, 0, 0, 937840050 )Call CreateTimeSpan( 1111, 2222, 3333, 4444, 5555 )Call CreateTimeSpan( 1111, -2222, -3333, -4444, -5555 )Call CreateTimeSpan( 99999, 99999, 99999, 99999, 99999 )System.TimeSpan FieldsName DescriptionMaxValue 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-onlyTimeSpan.MaxValue FieldRepresents the maximum TimeSpan value. This field is read-only.The value of this field is equivalent to Int64.MaxValue ticks. The stringrepresentation of this value is positive 10675199.02:48:05.4775807.The following code example references and displays the value of the MaxValue field.Option ExplicitDim timeSpanSet timeSpan = DotNetFactory.CreateInstance( "System.TimeSpan" )Print _
  • 99. Chapter 14 Scripting Quicktest Professional Page 99Dani Vainstein DotNetFactory Page 99 of 151"This example of the fields of the TimeSpan class" & _vbCrLf & "generates the following output." & vbCrLf ** Display the maximum, minimum, and zero TimeSpan values.Print "Maximum TimeSpan ---> " & timeSpan.MaxValue.ToString()Print "Minimum TimeSpan ---> " & timeSpan.MinValue.ToString()Print "Zero TimeSpan ---> " & timeSpan.Zero.ToString()Print "Ticks per day ---> " & timeSpan.TicksPerDay.ToString()Print "Ticks per hour ---> " & timeSpan.TicksPerHour.ToString()Print "Ticks per minute ---> " & timeSpan.TicksPerMinute.ToString()Print "Ticks per second ---> " & timeSpan.TicksPerSecond.ToString()Print "Ticks per millisecond ---> " & timeSpan.TicksPerMillisecond.ToString()Set timeSpan = NothingTimeSpan.MinValue FieldRepresents the minimum TimeSpan value. This field is read-only.The value of this field is equivalent to Int64.MinValue ticks. The string representationof this value is negative 10675199.02:48:05.4775808.TimeSpan.TicksPerDay FieldRepresents the number of ticks in 1 day. This field is constant.The value of this constant is 864 billion; that is, 864,000,000,000.TimeSpan.TicksPerHour FieldRepresents the number of ticks in 1 hour. This field is constant.The value of this constant is 36 billion; that is, 36,000,000,000.
  • 100. Chapter 14 Scripting Quicktest Professional Page 100Dani Vainstein DotNetFactory Page 100 of 151TimeSpan.TicksPerMillisecond FieldRepresents the number of ticks in 1 millisecond. This field is constant.The value of this constant is 10 thousand; that is, 10,000.TimeSpan.TicksPerMinute FieldRepresents the number of ticks in 1 minute. This field is constantThe value of this constant is 600 million; that is, 600,000,000.TimeSpan.TicksPerSecond FieldRepresents the number of ticks in 1 second.The value of this constant is 10 million; that is, 10,000,000TimeSpan.Zero FieldRepresents the zero TimeSpan value. This field is read-only.This constant provides a convenient source for zero in time calculations.TimeSpan PropertiesName DescriptionDaysGets the number of whole days represented by the current TimeSpanstructure.HoursGets the number of whole hours represented by the current TimeSpanstructure.MillisecondsGets the number of whole milliseconds represented by the currentTimeSpan structure.MinutesGets the number of whole seconds represented by the currentTimeSpan structure.SecondsGets the number of whole seconds represented by the currentTimeSpan structure.TicksGets the number of ticks that represent the value of the currentTimeSpan structure.
  • 101. Chapter 14 Scripting Quicktest Professional Page 101Dani Vainstein DotNetFactory Page 101 of 151TotalDaysGets the value of the current TimeSpan structure expressed in wholeand fractional days.TotalHoursGets the value of the current TimeSpan structure expressed in wholeand fractional hours.TotalMillisecondsGets the value of the current TimeSpan structure expressed in wholeand fractional milliseconds.TotalMinutesGets the value of the current TimeSpan structure expressed in wholeand fractional minutes.TotalSecondsGets the value of the current TimeSpan structure expressed in wholeand fractional seconds.TimeSpan.Days PropertyGets the number of whole days represented by the current TimeSpan structure.returnValue = object.DaysThe day component of this instance. The return value can be positive or negative.A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optionalminus sign indicates a negative time interval, the d component is days, hh is hoursas measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions ofa second. The value of the Days property is the day component, d.The following code example creates several TimeSpan objects and displays the Daysproperty of each.Option ExplicitDim timeSpan, int64 ** Display the properties of the TimeSpan parameter.Sub ShowTimeSpanProperties( Byref interval )Print "Interval : " & interval.ToString()Print "Days : " & interval.Days & vbTab & _"TotalDays : " & interval.TotalDaysPrint "Hours : " & interval.Hours & vbTab & _"TotalHours : " & interval.TotalHoursPrint "Minutes : " & interval.Minutes & vbTab & _"TotalMinutes : " & interval.TotalMinutesPrint "Seconds : " & interval.Seconds & vbTab & _"TotalSeconds : " & interval.TotalSecondsPrint "Milliseconds : " & interval.Milliseconds & vbTab & _"TotalMilliseconds : " & interval.TotalMillisecondsPrint "Ticks : " & interval.Ticks
  • 102. Chapter 14 Scripting Quicktest Professional Page 102Dani Vainstein DotNetFactory Page 102 of 151End SubPrint "This example of the TimeSpan class properties " & _"generates the " & vbCrLf & "following output. It " & _"creates several TimeSpan objects and " & vbCrLf & _"displays the values of the TimeSpan properties for " & _"each." ** Create and display a TimeSpan value of 1 tick.Print "TimeSpan( 1 )"Set timeSpan = DotNetFactory.CreateInstance( "System.TimeSpan",, 1 )Call ShowTimeSpanProperties( timeSpan ) ** Create a TimeSpan value with a large number of ticks.Print vbCrLf & "TimeSpan( 111222333444555 )"Set int64 = DotNetFactory.CreateInstance( _"System.Int64" ).Parse( "111222333444555" )Set timeSpan = DotNetFactory.CreateInstance( "System.TimeSpan",, int64 )Call ShowTimeSpanProperties( timeSpan )Set int64 = Nothing ** This TimeSpan has all fields specified.Print vbCrLf & "TimeSpan( 10, 20, 30, 40, 50 )"Set timeSpan = DotNetFactory.CreateInstance( "System.TimeSpan",,10, 20, 30, 40, 50 )Call ShowTimeSpanProperties( timeSpan ) ** This TimeSpan has all fields overflowing.Print vbCrLf & "TimeSpan( 1111, 2222, 3333, 4444, 5555 )"Set timeSpan = DotNetFactory.CreateInstance( _"System.TimeSpan",,1111, 2222, 3333, 4444, 5555 )Call ShowTimeSpanProperties( timeSpan ) ** This TimeSpan is based on a number of days.Print vbCrLf & "FromDays( 20.84745602 )"Set timeSpan = DotNetFactory.CreateInstance( _"System.TimeSpan" ).FromDays( 20.84745602 )Call ShowTimeSpanProperties( timeSpan )Set timeSpan = Nothing
  • 103. Chapter 14 Scripting Quicktest Professional Page 103Dani Vainstein DotNetFactory Page 103 of 151TimeSpan.Hours PropertyGets the number of whole days represented by the current TimeSpan structure.
  • 104. Chapter 14 Scripting Quicktest Professional Page 104Dani Vainstein DotNetFactory Page 104 of 151returnValue = object.HoursThe day component of this instance. The return value can be positive or negative.A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optionalminus sign indicates a negative time interval, the d component is days, hh is hoursas measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions ofa second. The value of the Days property is the day component, d.The following code example creates several TimeSpan objects and displays the Hoursproperty of each. See Example TimeSpan PropertiesTimeSpan.Milliseconds PropertyGets the number of whole milliseconds represented by the current TimeSpan structure.returnValue = object.MillisecondsThe millisecond component of the current TimeSpan structure. The return value rangesfrom -999 through 999.A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optionalminus sign indicates a negative time interval, the d component is days, hh is hoursas measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions ofa second. The value of the Days property is the day component, d.The following code example creates several TimeSpan objects and displays theMilliseconds property of each. See Example TimeSpan PropertiesTimeSpan.Minutes PropertyGets the number of whole minutes represented by the current TimeSpan structure.returnValue = object.MinutesThe minute component of the current TimeSpan structure. The return value ranges from-59 through 59.A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional
  • 105. Chapter 14 Scripting Quicktest Professional Page 105Dani Vainstein DotNetFactory Page 105 of 151minus sign indicates a negative time interval, the d component is days, hh is hoursas measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions ofa second. The value of the Minutes property is the minute component, mm.The following code example creates several TimeSpan objects and displays theMinutes property of each. See Example TimeSpan PropertiesTimeSpan.Seconds PropertyGets the number of whole seconds represented by the current TimeSpan structure.returnValue = object.SecondsThe second component of the current TimeSpan structure. The return value ranges from-59 through 59.A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optionalminus sign indicates a negative time interval, the d component is days, hh is hoursas measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions ofa second. The value of the Seconds property is the seconds component, ss.The following code example creates several TimeSpan objects and displays theSeconds property of each. See Example TimeSpan PropertiesTimeSpan.Ticks PropertyGets the number of ticks that represent the value of the current TimeSpan structure.returnValue = object.TicksThe number of ticks contained in this instance.The smallest unit of time is the tick, which is equal to 100 nanoseconds. A tick canbe negative or positive.The following code example creates several TimeSpan objects and displays the Ticksproperty of each. See Example TimeSpan PropertiesTimeSpan.TotalDays Property
  • 106. Chapter 14 Scripting Quicktest Professional Page 106Dani Vainstein DotNetFactory Page 106 of 151Gets the value of the current TimeSpan structure expressed in whole and fractionaldays.returnValue = object.TotalDaysThe total number of days represented by this instance.This property converts the value of this instance from ticks to days. This numbermight include whole and fractional daysThe following code example creates several TimeSpan objects and displays theTotalDays property of each. See Example TimeSpan PropertiesTimeSpan.TotalHours PropertyGets the value of the current TimeSpan structure expressed in whole and fractionalhours.returnValue = object.TotalHoursThe total number of hours represented by this instance.This property converts the value of this instance from ticks to hours. This numbermight include whole and fractional hours.The following code example creates several TimeSpan objects and displays theTotalHours property of each. See Example TimeSpan PropertiesTimeSpan.TotalMilliseconds PropertyGets the value of the current TimeSpan structure expressed in whole and fractionalmilliseconds.returnValue = object.TotalMillisecondsThe total number of milliseconds represented by this instance.This property converts the value of this instance from ticks to milliseconds. This
  • 107. Chapter 14 Scripting Quicktest Professional Page 107Dani Vainstein DotNetFactory Page 107 of 151number might include whole and fractional milliseconds..The following code example creates several TimeSpan objects and displays theTotalMilliseconds property of each. See Example TimeSpan PropertiesTimeSpan.TotalMinutes PropertyGets the value of the current TimeSpan structure expressed in whole and fractionalminutes.returnValue = object.TotalMinutesThe total number of minutes represented by this instance.This property converts the value of this instance from ticks to minutes. This numbermight include whole and fractional minutes.The following code example creates several TimeSpan objects and displays theTotalMinutes property of each. See Example TimeSpan PropertiesTimeSpan.TotalSeconds PropertyGets the value of the current TimeSpan structure expressed in whole and fractionalseconds.returnValue = object.TotalSecondsThe total number of seconds represented by this instance.This property converts the value of this instance from ticks to seconds. This numbermight include whole and fractional seconds..The following code example creates several TimeSpan objects and displays theTotalSeconds property of each. See Example TimeSpan PropertiesTimeSpan MethodsName DescriptionAdd Adds the specified TimeSpan to this instance.
  • 108. Chapter 14 Scripting Quicktest Professional Page 108Dani Vainstein DotNetFactory Page 108 of 151CompareCompares two TimeSpan values and returns an integer thatindicates their relationship.CompareToOverloaded. Compares this instance to a specified object orTimeSpan and returns an indication of their relative values.DurationReturns a new TimeSpan object whose value is the absolutevalue of the current TimeSpan object.EqualsOverloaded. Overridden. Returns a value indicating whether twoinstances of TimeSpan are equal.FomDaysReturns a TimeSpan that represents a specified number of days,where the specification is accurate to the nearest millisecond.FromHoursReturns a TimeSpan that represents a specified number ofhours, where the specification is accurate to the nearestmillisecond.FromMillsecondReturns a TimeSpan that represents a specified number ofmilliseconds.FromMinutesReturns a TimeSpan that represents a specified number ofminutes, where the specification is accurate to the nearestmillisecond.FromSecondsReturns a TimeSpan that represents a specified number ofseconds, where the specification is accurate to the nearestmillisecond.FromTicksReturns a TimeSpan that represents a specified time, where thespecification is in units of ticks.GetHashCode Overridden. Returns a hash code for this instanceGetType Gets the Type of the current instanceNegateReturns a TimeSpan whose value is the negated value of thisinstance.op_Addition Adds two specified TimeSpan instances.op_Equality Indicates whether two TimeSpan instances are equal.op_GreaterThanIndicates whether a specified TimeSpan is greater than anotherspecified TimeSpan.op_GreaterThanOrEqualIndicates whether a specified TimeSpan is greater than or equalto another specified TimeSpan.op_Inequality Indicates whether two TimeSpan instances are not equal.op_LessThanIndicates whether a specified TimeSpan is less than anotherspecified TimeSpan.op_LessThanOrEqualIndicates whether a specified TimeSpan is less than or equal toanother specified TimeSpan.op_SubtractionSubtracts a specified TimeSpan from another specifiedTimeSpan.op_UnaryNegationReturns a TimeSpan whose value is the negated value of thespecified instance.op_UnaryPlus Returns the specified instance of TimeSpan.ParseConstructs a new TimeSpan object from a time interval specifiedin a string.
  • 109. Chapter 14 Scripting Quicktest Professional Page 109Dani Vainstein DotNetFactory Page 109 of 151Subtract Subtracts the specified TimeSpan from this instance.ToStringOverridden. Returns the string representation of the value of thisinstance.TryParseConstructs a new TimeSpan object from a time interval specifiedin a string. Parameters specify the time interval and the variablewhere the new TimeSpan object is returned.TimeSpan.Add ( TimeSpan ) MethodAdds the specified TimeSpan to this instance.Set object = instance.Add( ts )Parameter Descriptionts A TimeSpanA TimeSpan that represents the value of this instance plus the value of ts.OverflowException - The resulting TimeSpan is less than MinValue or greater thanMaxValue.The return value must be between MinValue and MaxValue; otherwise, anexception is thrown.The return value is a new TimeSpan; the original TimeSpan is not modified.The following code example creates several pairs of TimeSpan objects and calculatestheir sum with the Add method.Option ExplicitDim tsL, tsR, int64_1, int64_2Sub ShowTimeSpanSumDiff( ByRef tsLeft, ByRef tsRight )Print vbCrLf &"TimeSpan Left : " & tsLeftPrint "TimeSpan Right : " & tsRightPrint "Left.Add( Right ) : " & tsLeft.Add( tsRight )Print "Left.Subtract( Right ) : " & tsLeft.Subtract( tsRight )End SubPrint "This example of the TimeSpan.Add( ) and " & _"TimeSpan.Subtract( ) " & vbCrLf & "methods " & _"generates the following output by creating several " & _vbCrLf & "pairs of TimeSpan objects and calculating " & _"and displaying " & vbCrLf & "the sum " & _
  • 110. Chapter 14 Scripting Quicktest Professional Page 110Dani Vainstein DotNetFactory Page 110 of 151"and difference of each." ** Create pairs of TimeSpan objects.Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan", ,1, 20, 0 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan", ,0, 45, 10 )Call ShowTimeSpanSumDiff( tsL, tsR )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan", ,1, 10, 20, 30, 40 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan", ,-1, 2, 3, 4, 5 )Call ShowTimeSpanSumDiff( tsL, tsR )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan", ,182, 12, 30, 30, 505 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan", ,182, 11, 29, 29, 495 )Call ShowTimeSpanSumDiff( tsL, tsR )Set int64_1 = DotNetFactory.CreateInstance( _"System.Int64" ).Parse( "888888888888888" )Set int64_2= DotNetFactory.CreateInstance( _"System.Int64" ).Parse( "999999999999999" )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan", , int64_1 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan", , int64_2 )Call ShowTimeSpanSumDiff( tsL, tsR )Set tsL = Nothing : Set tsR = NothingSet int64_1 = Nothing : Set int64_2 = NothingDateTime.Compare ( TimeSpan, TimeSpan ) MethodCompares two TimeSpan values and returns an integer that indicates their relationship.
  • 111. Chapter 14 Scripting Quicktest Professional Page 111Dani Vainstein DotNetFactory Page 111 of 151returnValue = instance.Compare( t1, t2 )Parameter Descriptiont1 The first DateTime.t2 The second DateTime.A signed number indicating the relative values of t1 and t2Less than zero - t1 is less than t2.Zero - t1 equals t2Greater than zero - t1 is greater than t2.The following code example compares several TimeSpan objects to a referenceTimeSpan using the Compare method.Option ExplicitDim ts, tsL, tsR, int64 ** Compare TimeSpan parameters, and display them with the results.Sub CompareTimeSpans( ByRef tsLeft, ByRef tsRight, ByVal RightText )Dim sbPrint "Right : " & RightText & " ---> " & tsRightPrint "TimeSpan.Equals( Left, Right ) ---> " & ts.Equals( tsLeft, tsRight )Print "TimeSpan.Compare( Left, Right ) ---> " & ts.Compare( tsLeft, tsRight )End SubSet ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",,2, 0, 0 )Print "This example of the TimeSpan.Equals( TimeSpan, " & _"TimeSpan ) and " & vbCrLf & "TimeSpan.Compare( " & _"TimeSpan, TimeSpan ) methods generates the " & vbCrLf & _"following output by creating several " & _"different TimeSpan " & vbCrLf & "objects and " & _"comparing them with a 2-hour TimeSpan." & vbCrLfPrint vbNewLinePrint "Left: TimeSpan( 2, 0, 0 ) ---> " & tsL ** Create objects to compare with a 2-hour TimeSpan.Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 120, 0 )Call CompareTimeSpans( tsL, tsR, "TimeSpan( 0, 120, 0 )" )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 2, 0, 1 )Call CompareTimeSpans( tsL, tsR, "TimeSpan( 2, 0, 1 )" )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 2, 0, -1 )Call CompareTimeSpans( tsL, tsR, "TimeSpan( 2, 0, -1 )" )Set int64 = DotNetFactory.CreateInstance( "System.Int64" ).Parse( "72000000000" )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, int64 )
  • 112. Chapter 14 Scripting Quicktest Professional Page 112Dani Vainstein DotNetFactory Page 112 of 151Call CompareTimeSpans( tsL, tsR, "TimeSpan( 72000000000 )" )Set int64 = NothingSet tsr = ts.FromDays( 1 / 12 )Call CompareTimeSpans( tsL, tsR, "TimeSpan.FromDays( 1 / 12 )" )Set ts = Nothing : Set tsL = Nothing : Set tsR = NothingTimeSpan.CompareTo ( TimeSpan ) MethodCompares this instance to a specified TimeSpan object and returns an indication of theirrelative values.returnValue = instance.CompareTo( value )Parameter Descriptionvalue A TimeSpan object to compare to this instance.A signed number indicating the relative values of t1 and t2Less than zero - t1 is less than t2.Zero - t1 equals t2Greater than zero - t1 is greater than t2.
  • 113. Chapter 14 Scripting Quicktest Professional Page 113Dani Vainstein DotNetFactory Page 113 of 151This method implements the System.IComparable interface and performs slightlybetter than the TimeSpan.CompareTo method because it does not have to convertthe value parameter to an object.TimeSpan.Duration ( ) MethodReturns a new TimeSpan object whose value is the absolute value of the currentTimeSpan object.Set ts = instance.Duration()A new TimeSpan whose value is the absolute value of the current TimeSpanobject. ExampleOverflowException - The value of this instance is MinValue.The following code example applies the Duration method to several TimeSpan objects.Option ExplicitDim ts, unaryTsSub ShowDurationNegate( Byref interval ) ** Display the TimeSpan value and the results of the Duration and Negate methods.Print "Interval ---> " & intervalPrint "Interval.Duration ---> " & interval.DurationPrint "Interval.Negate ---> " & interval.NegateEnd SubPrint "This example of TimeSpan.Duration( ), " & _"TimeSpan.Negate( ), " & vbCrLf & _"and the TimeSpan Unary Negation and " & _"Unary Plus operators " & vbCrLf & _"generates the following output." & vbCrLf ** Create TimeSpan objects and apply the Unary Negation and Unary Plus operators to them.Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1 )Call ShowDurationNegate( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, -1234567 )Call ShowDurationNegate( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 0, 10, -20, -30 )Set unaryTs = DotNetFactory.CreateInstance( "System.TimeSpan" ).op_UnaryPlus( ts )
  • 114. Chapter 14 Scripting Quicktest Professional Page 114Dani Vainstein DotNetFactory Page 114 of 151Call 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 = NothingTimeSpan.Equals MethodName DescriptionTimeSpan.Equals (TimeSpan)Returns a value indicating whether this instance is equalto a specified TimeSpan object.TimeSpan.Equals (TimeSpan,TimeSpan)Returns a value indicating whether two specifiedinstances of TimeSpan are equal.TimeSpan.Equals ( TimeSpan ) MethodReturns a value indicating whether two specified instances of TimeSpan are equal.
  • 115. Chapter 14 Scripting Quicktest Professional Page 115Dani Vainstein DotNetFactory Page 115 of 151returnValue = instance.Equals( obj )Parameter Descriptionobj A TimeSpan object to compare with this instance.true if obj represents the same time interval as this instance; otherwise, false.This method implements the System.IEquatable interface, and performs slightlybetter than Equals because it does not have to convert the the obj parameter to anobject.The following code example compares several TimeSpan objects to a referenceTimeSpan using the Equals method. See Example Time Span CompareTimeSpan.Equals ( TimeSpan, TimeSpan ) MethodReturns a value indicating whether two specified instances of TimeSpan are equalreturnValue = instance.Equals( t1, t2 )Parameter Descriptiont1 A TimeSpant2 A TimeSpantrue if the values of t1 and t2 are equal; otherwise, falseThe following code example compares several TimeSpan objects to a referenceTimeSpan using the Equals method. See Example Time Span CompareTimeSpan.FromDays ( Double ) MethodReturns a TimeSpan that represents a specified number of days, where the specificationis accurate to the nearest millisecond.Set ts = instance.fromDays( value )
  • 116. Chapter 14 Scripting Quicktest Professional Page 116Dani Vainstein DotNetFactory Page 116 of 151Parameter Descriptionvalue A number of days, accurate to the nearest millisecond.TimeSpan that represents valueOverflowException - value is less than MinValue or greater than MaxValue.ArgumentException - value is equal to Double.NaN.The value parameter is converted to milliseconds, which is converted to ticks, andthat number of ticks is used to intialize the new TimeSpan. Therefore, value willonly be considered accurate to the nearest millisecond.If value is Double.PositiveInfinity, MaxValue is returned. If value isDouble.NegativeInfinity, MinValue is returned.The following code example creates several TimeSpan objects using the FromDaysmethod.Option ExplicitDim tsSub 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 ---> " & daysPrint "time Interval ---> " & timeIntervalSet interval = NothingEnd SubPrint "This example of TimeSpan.FromDays( Double )" & vbCrLf & _"generates the following output." & vbCrLfSet ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Call GenTimeSpanFromDays( 0.000000006 )Call GenTimeSpanFromDays( 0.000000017 )Call GenTimeSpanFromDays( 0.000123456 )Call GenTimeSpanFromDays( 1.234567898 )Call GenTimeSpanFromDays( 12345.678987654 )Call GenTimeSpanFromDays( 0.000011574 )Call GenTimeSpanFromDays( 0.000694444 )Call GenTimeSpanFromDays( 0.041666666 )Call GenTimeSpanFromDays( 1 )Call GenTimeSpanFromDays( 20.84745602 )Set ts = Nothing
  • 117. Chapter 14 Scripting Quicktest Professional Page 117Dani Vainstein DotNetFactory Page 117 of 151TimeSpan.FromHours ( Double ) MethodReturns a TimeSpan that represents a specified number of hours, where thespecification is accurate to the nearest millisecond.Set ts = instance.fromHours( value )Parameter Descriptionvalue A number of hours accurate to the nearest millisecond.A TimeSpan that represents valueOverflowException - value is less than MinValue or greater than MaxValue.ArgumentException - value is equal to Double.NaN.The value parameter is converted to milliseconds, which is converted to ticks, andthat number of ticks is used to intialize the new TimeSpan. Therefore, value willonly be considered accurate to the nearest millisecond.If value is Double.PositiveInfinity, MaxValue is returned. If value is
  • 118. Chapter 14 Scripting Quicktest Professional Page 118Dani Vainstein DotNetFactory Page 118 of 151Double.NegativeInfinity, MinValue is returned.The following code example creates several TimeSpan objects using the FromHoursmethod.Option ExplicitDim tsSub 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 ---> " & hoursPrint "time Interval ---> " & timeIntervalSet interval = NothingEnd SubPrint "This example of TimeSpan.FromHours( Double )" & _vbCrLf & "generates the following output." & vbCrLfSet ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Call GenTimeSpanFromHours ( 0.0000002 )Call GenTimeSpanFromHours ( 0.0000003 )Call GenTimeSpanFromHours ( 0.0012345 )Call GenTimeSpanFromHours ( 12.3456789 )Call GenTimeSpanFromHours ( 123456.7898765 )Call GenTimeSpanFromHours ( 0.0002777 )Call GenTimeSpanFromHours ( 0.0166666 )Call GenTimeSpanFromHours ( 1 )Call GenTimeSpanFromHours ( 24 )Call GenTimeSpanFromHours( 500.3389445 )Set ts = Nothing
  • 119. Chapter 14 Scripting Quicktest Professional Page 119Dani Vainstein DotNetFactory Page 119 of 151TimeSpan.FromMilliseconds ( Double ) MethodReturns a TimeSpan that represents a specified number of milliseconds.Set ts = instance.fromMilliseconds( value )Parameter Descriptionvalue A number of milliseconds.A TimeSpan that represents valueOverflowException - value is less than MinValue or greater than MaxValue.ArgumentException - value is equal to Double.NaN.The value parameter is converted to milliseconds, which is converted to ticks, andthat number of ticks is used to intialize the new TimeSpan. Therefore, value willonly be considered accurate to the nearest millisecond.If value is Double.PositiveInfinity, MaxValue is returned. If value isDouble.NegativeInfinity, MinValue is returned.
  • 120. Chapter 14 Scripting Quicktest Professional Page 120Dani Vainstein DotNetFactory Page 120 of 151The following code example creates several TimeSpan objects using the FromHoursmethod.Option ExplicitDim tsSub 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 ---> " & millisecPrint "time Interval ---> " & timeIntervalSet interval = NothingEnd SubPrint "This example of TimeSpan.FromMilliseconds ( Double )" & _vbCrLf & "generates the following output." & vbCrLfSet ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Call GenTimeSpanFromMillisec ( 1 )Call GenTimeSpanFromMillisec ( 1.5 )Call GenTimeSpanFromMillisec ( 12345.6 )Call GenTimeSpanFromMillisec ( 123456789.8 )Call GenTimeSpanFromMillisec ( 1234567898765.4 )Call GenTimeSpanFromMillisec ( 1000 )Call GenTimeSpanFromMillisec ( 60000 )Call GenTimeSpanFromMillisec ( 3600000 )Call GenTimeSpanFromMillisec ( 86400000 )Call GenTimeSpanFromMillisec ( 1801220200 )Set ts = Nothing
  • 121. Chapter 14 Scripting Quicktest Professional Page 121Dani Vainstein DotNetFactory Page 121 of 151TimeSpan.FromMinutes ( Double ) MethodReturns a TimeSpan that represents a specified number of minutes, where thespecification is accurate to the nearest millisecond.Set ts = instance.FromMinutes( value )Parameter Descriptionvalue A number of minutes, accurate to the nearest millisecond.A TimeSpan that represents value.OverflowException - value is less than MinValue or greater than MaxValue.ArgumentException - value is equal to Double.NaN.The value parameter is converted to milliseconds, which is converted to ticks, andthat number of ticks is used to intialize the new TimeSpan. Therefore, value willonly be considered accurate to the nearest millisecond.If value is Double.PositiveInfinity, MaxValue is returned. If value is
  • 122. Chapter 14 Scripting Quicktest Professional Page 122Dani Vainstein DotNetFactory Page 122 of 151Double.NegativeInfinity, MinValue is returned.TimeSpan.FromSeconds ( Double ) MethodReturns a TimeSpan that represents a specified number of seconds, where thespecification is accurate to the nearest millisecond.Set ts = instance.FromSeconds( value )Parameter Descriptionvalue A number of seconds, accurate to the nearest millisecond.A TimeSpan that represents value.OverflowException - value is less than MinValue or greater than MaxValue.ArgumentException - value is equal to Double.NaN.The value parameter is converted to milliseconds, which is converted to ticks, andthat number of ticks is used to intialize the new TimeSpan. Therefore, value willonly be considered accurate to the nearest millisecond.If value is Double.PositiveInfinity, MaxValue is returned. If value isDouble.NegativeInfinity, MinValue is returned.The following code example creates several TimeSpan objects using the FromHoursmethod.Option ExplicitDim tsSub 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 ---> " & secondsPrint "time Interval ---> " & timeIntervalSet interval = NothingEnd SubPrint "This example of TimeSpan.FromMinutes ( Double )" & _vbCrLf & "generates the following output." & vbCrLfSet ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Call GenTimeSpanFromSeconds ( 0.001 )Call GenTimeSpanFromSeconds ( 0.0015 )Call GenTimeSpanFromSeconds ( 12.3456 )
  • 123. Chapter 14 Scripting Quicktest Professional Page 123Dani Vainstein DotNetFactory Page 123 of 151Call GenTimeSpanFromSeconds ( 123456.7898 )Call GenTimeSpanFromSeconds ( 1234567898.7654 )Call GenTimeSpanFromSeconds ( 1 )Call GenTimeSpanFromSeconds ( 60 )Call GenTimeSpanFromSeconds ( 3600 )Call GenTimeSpanFromSeconds ( 86400 )Call GenTimeSpanFromSeconds ( 1801220.2 )Set ts = NothingTimeSpan.FromTicks ( Long ) MethodReturns a TimeSpan that represents a specified time, where the specification is in unitsof ticks.Set ts = instance.FromTicks( value )Parameter Descriptionvalue A number of ticks that represent a time.A TimeSpan that represents value.
  • 124. Chapter 14 Scripting Quicktest Professional Page 124Dani Vainstein DotNetFactory Page 124 of 151This is a convenience method with the same behavior as the TimeSpan constructor.TimeSpan.GetHashCode ( ) MethodReturns a TimeSpan that represents a specified time, where the specification is in unitsof ticks.returnValue = instance.GetHashCode()A 32-bit signed integer hash code.Two TimeSpan objects might have the same hash code even though they representdifferent time values.The following code example generates the hash codes of several TimeSpan objectsusing the GetHashCode method.Option ExplicitDim ts, int64Sub DisplayHashCode( ByRef interval )Dim timeInterval, hashCode ** 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 SubPrint "This example of TimeSpan.GetHashCode( ) generates " & _"the following " & vbCrLf & "output, which displays " & _"the hash codes of representative TimeSpan " & vbCrLf & _"objects in hexadecimal and decimal formats." & vbCrLfSet ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 0, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 1, 0 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 0, 0 )Call DisplayHashCode( ts )Set int64 = DotNetFactory.CreateInstance( "System.Int64" ).Parse( "36000000001" )
  • 125. Chapter 14 Scripting Quicktest Professional Page 125Dani Vainstein DotNetFactory Page 125 of 151Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, int64 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 1, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 0, 0, 0 )Call DisplayHashCode( ts )Set int64 = DotNetFactory.CreateInstance( "System.Int64" ).Parse( "864000000001" )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, int64 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 0, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 100, 0, 0, 0 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 100, 0, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 00, 0, 0, 1 )Call DisplayHashCode( ts )Set ts = NothingTimeSpan.Negate ( ) MethodReturns a TimeSpan whose value is the negated value of this instance.
  • 126. Chapter 14 Scripting Quicktest Professional Page 126Dani Vainstein DotNetFactory Page 126 of 151returnValue = 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 representdifferent time values.OverflowException - The negated value of this instance cannot be represented by aTimeSpan; that is, the value of this instance is MinValue.TimeSpan.op_Addition ( TimeSpan, TimeSpan ) MethodAdds two specified TimeSpan instances.Set ts = instance.op_Addition( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.A TimeSpan whose value is the sum of the values of t1 and t2.OverflowException - The resulting TimeSpan is less than MinValue or greater thanMaxValue.The following code example creates several pairs of TimeSpan objects and calculatestheir sum with the Addition operator.Option ExplicitDim ts, tsL, tsR, int64L, int64R ** Display TimeSpan parameters and their sum and difference.Private Sub ShowTimeSpanSumDiff( ByRef tsLeft, ByRef tsRight )Print "TimeSpan Left : " & tsLeft.ToString()Print "TimeSpan Right : " & tsRight.ToString()Print "TimeSpan.op_Addition( Left, Right )" & ts.op_Addition( tsLeft, tsRight )Print "TimeSpan.op_Subtraction( Left, Right )" & ts.op_Subtraction( tsLeft, tsRight)Print String( 50, "*" )End Sub
  • 127. Chapter 14 Scripting Quicktest Professional Page 127Dani Vainstein DotNetFactory Page 127 of 151Print "This example of the TimeSpan Addition and " & _"Subtraction " & vbCrLf & "operators " & _"generates the following output by creating " & vbCrLf & _"several pairs of TimeSpan objects and calculating " & _"and " & vbCrLf & "displaying the sum " & _"and difference of each." & vbCrLf ** Create pairs of TimeSpan objects.Set ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 20, 0 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 45, 10 )Call ShowTimeSpanSumDiff( tsL, tsR )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 10, 20, 30, 40 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, -1, 2, 3, 4, 5 )Call ShowTimeSpanSumDiff( tsL, tsR )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",, 182, 12, 30, 30, 505 )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 182, 11, 29, 29, 495 )Call ShowTimeSpanSumDiff( tsL, tsR )Set int64L = DotNetFactory.CreateInstance("System.Int64").Parse( "888888888888888" )Set int64R = DotNetFactory.CreateInstance("System.Int64").Parse( "999999999999999" )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",, int64L )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, int64R )Call ShowTimeSpanSumDiff( tsL, tsR )Set int64L = Nothing : Set int64R = NothingSet tsL = Nothing : Set tsR = NothingSet ts = Nothing
  • 128. Chapter 14 Scripting Quicktest Professional Page 128Dani Vainstein DotNetFactory Page 128 of 151TimeSpan.op_Equality ( TimeSpan, TimeSpan ) MethodIndicates whether two TimeSpan instances are equalreturnValue = instance.op_Equality( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.true if the values of t1 and t2 are equal; otherwise, false.The following code example compares several TimeSpan objects to a referenceTimeSpan using the Equality operator.Option ExplicitDim ts, tsL, tsR ** 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 SubPrint "This example of the TimeSpan relational operators " & _"generates " & vbCrLf & "the following output. It " & _"creates several different TimeSpan " & vbCrLf & _"objects and compares them with a 2-hour TimeSpan." & vbCrLf ** Create Main TimeSpan objectSet ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",, 2, 0, 0 ) ** Create objects to compare with a 2-hour TimeSpan.
  • 129. Chapter 14 Scripting Quicktest Professional Page 129Dani Vainstein DotNetFactory Page 129 of 151Print "Left : TimeSpan( 2, 0, 0 ) ---> " & tsLSet tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, 120, 0 )Call CompareTimeSpans( tsL, tsr, "TimeSpan( 0, 120, 0 )" )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 2, 0, 1 )Call CompareTimeSpans( tsL, tsr, "TimeSpan( 2, 0, 1 )" )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan",, 2, 0, -1 )Call CompareTimeSpans( tsL, tsr, "TimeSpan( 2, 0, -1 )" )Set tsR = DotNetFactory.CreateInstance( "System.TimeSpan" ).FromDays( 1 / 12 )Call CompareTimeSpans( tsL, tsr, "TimeSpan.FromDays( 1 / 12 )" )Set tsL = Nothing : Set tsR = NothingSet ts = Nothing
  • 130. Chapter 14 Scripting Quicktest Professional Page 130Dani Vainstein DotNetFactory Page 130 of 151TimeSpan.op_GreaterThan ( TimeSpan, TimeSpan )MethodIndicates whether a specified TimeSpan is greater than another specified TimeSpan.returnValue = instance.op_GreaterThan( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.true if the value of t1 is greater than the value of t2; otherwise, false.The following code example compares several TimeSpan objects to a referenceTimeSpan using the GreaterThan operator. See TimeSpan.op_Equality ExampleTimeSpan.op_GreaterThanOrEqual ( TimeSpan, TimeSpan) MethodIndicates whether a specified TimeSpan is greater than or equal to another specifiedTimeSpan.returnValue = instance.op_GreaterThanOrEqual( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.true if the value of t1 is greater than or equal to the value of t2; otherwise, false.The following code example compares several TimeSpan objects to a referenceTimeSpan using the GreaterThanOrEqual operator.See TimeSpan.op_Equality ExampleTimeSpan.op_Inequality ( TimeSpan, TimeSpan ) Method
  • 131. Chapter 14 Scripting Quicktest Professional Page 131Dani Vainstein DotNetFactory Page 131 of 151Indicates whether two TimeSpan instances are not equal.returnValue = instance.op_Inequality( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.true if the values of t1 and t2 are not equal; otherwise, false.The following code example compares several TimeSpan objects to a referenceTimeSpan using the Inequality operator.See TimeSpan.op_Equality ExampleTimeSpan.op_LessThan ( TimeSpan, TimeSpan ) MethodIndicates whether a specified TimeSpan is less than another specified TimeSpan.returnValue = instance.op_LessThan( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.true if the value of t1 is less than the value of t2; otherwise, false.The following code example compares several TimeSpan objects to a referenceTimeSpan using the LessThan operator. See TimeSpan.op_Equality ExampleTimeSpan.op_LessThanOrEqual ( TimeSpan, TimeSpan )MethodIndicates whether a specified TimeSpan is less than or equal to another specifiedTimeSpan.returnValue = instance.op_LessThanOrequal( t1, t2 )
  • 132. Chapter 14 Scripting Quicktest Professional Page 132Dani Vainstein DotNetFactory Page 132 of 151Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.true if the value of t1 is less than or equal to the value of t2; otherwise, false.The following code example compares several TimeSpan objects to a referenceTimeSpan using the LessThanOrEqual operator. See TimeSpan.op_Equality ExampleTimeSpan.op_Subtraction ( TimeSpan, TimeSpan ) MethodSubtracts a specified TimeSpan from another specified TimeSpan.Set ts = instance.op_Subtraction( t1, t2 )Parameter Descriptiont1 A TimeSpan.t2 A TimeSpan.A TimeSpan whose value is the result of the value of t1 minus the value of t2.OverflowException - The resulting TimeSpan is less than MinValue or greater thanMaxValue.The following code example creates several pairs of TimeSpan objects and calculatestheir difference with the Subtraction operator. See TimeSpan.op_Addition ExampleTimeSpan.op_UnaryNegation ( ) MethodReturns a TimeSpan whose value is the negated value of the specified instance.Set ts = instance.op_UnaryNegation( t )Parameter Descriptiont A TimeSpan
  • 133. Chapter 14 Scripting Quicktest Professional Page 133Dani Vainstein DotNetFactory Page 133 of 151A TimeSpan with the same numeric value as this instance, but the opposite sign.OverflowException - The negated value of this instance cannot be represented by aTimeSpan; that is, the value of this instance is MinValue.The following code example applies the op_UnaryNegation method to severalTimeSpan objects. See TimeSpan.Duration Method ExampleTimeSpan.op_UnaryPlus ( ) MethodReturns the specified instance of TimeSpan.Set ts = instance.op_UnaryPlus( t )Parameter Descriptiont A TimeSpanReturns t.The following code example applies the op_UnaryNegation method to severalTimeSpan objects. See TimeSpan.Duration Method ExampleTimeSpan.Parse ( String ) MethodConstructs a new TimeSpan object from a time interval specified in a string.Set ts = instance.Parse( s )Parameter Descriptions A string that specifies a time interval.A TimeSpan that corresponds to s.ArgumentNullException - s is a null reference (Nothing in Visual Basic).FormatException - s has an invalid format.
  • 134. Chapter 14 Scripting Quicktest Professional Page 134Dani Vainstein DotNetFactory Page 134 of 151OverflowExceptions represents a number less than MinValue or greater than MaxValueAt least one of the days, hours, minutes,or seconds components is outside its valid range.The s parameter contains a time interval specification of the form:[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]Items in square brackets ([ and ]) are optional; one selection from the list ofalternatives enclosed in braces ({ and }) and separated by vertical bars (|) isrequired; colons and periods (: and .) are literal characters and required; other itemsare as followsItem Descriptionws optional white space"-" optional minus sign indicating a negative TimeSpand days, ranging from 0 to 10675199hh hours, ranging from 0 to 23mm minutes, ranging from 0 to 59ss optional seconds, ranging from 0 to 59ff optional fractional seconds, consisting of 1 to 7 decimal digitsThe components of s must collectively specify a time interval greater than or equal toMinValue and less than or equal to MaxValueThe following code example uses the Parse method to create TimeSpan objects from validTimeSpan strings and to raise exceptions from invalid TimeSpan strings.Option ExplicitDim tsPrivate Sub ParseNDisplayTimeSpan( ByRef intervalStr )Dim intervalVal, intervalToStrOn Error Resume Next ** Write the first part of the output line. ** Parse the parameter, and then convert it back to a string.Set intervalVal = ts.Parse( intervalStr )If Err.Number <> 0 ThenPrint Err.DescriptionExit SubEnd IfintervalToStr = intervalVal.ToString( )Print "String to Parse ---> " & intervalStr & _" TimeSpan or Exception ---> " & intervalToStrEnd SubPrint "This example of TimeSpan.Parse( String ) and " & _vbCrLf & "TimeSpan.ToString( ) " & _"generates the following output." & vbCrLf
  • 135. Chapter 14 Scripting Quicktest Professional Page 135Dani Vainstein DotNetFactory Page 135 of 151Set ts = DotNetFactory.CreateInstance( "System.TimeSpan" )Call ParseNDisplayTimeSpan( "0" )Call ParseNDisplayTimeSpan( "14" )Call ParseNDisplayTimeSpan( "1:2:3" )Call ParseNDisplayTimeSpan( "0:0:0.250" )Call ParseNDisplayTimeSpan( "10.20:30:40.50" )Call ParseNDisplayTimeSpan( "99.23:59:59.9999999" )Call ParseNDisplayTimeSpan( "0023:0059:0059.0099" )Call ParseNDisplayTimeSpan( "24:0:0" )Call ParseNDisplayTimeSpan( "0:60:0" )Call ParseNDisplayTimeSpan( "0:0:60" )Call ParseNDisplayTimeSpan( "10:" )Call ParseNDisplayTimeSpan( ":10" )Call ParseNDisplayTimeSpan( "10:20:" )Call ParseNDisplayTimeSpan( ".123" )Call ParseNDisplayTimeSpan( "10." )Call ParseNDisplayTimeSpan( "10.12" )Set ts = NothingTimeSpan.Subtract ( TimeSpan ) MethodSubtracts the specified TimeSpan from this instance.Set object = instance.Subtract( ts )Parameter Descriptionts A TimeSpanA TimeSpan.
  • 136. Chapter 14 Scripting Quicktest Professional Page 136Dani Vainstein DotNetFactory Page 136 of 151OverflowException - The return value TimeSpan is less than MinValue or greaterthan MaxValue.The return value must be between MinValue and MaxValue; otherwise, anexception is thrown.The return value is a new TimeSpan; the original TimeSpan is not modified.The following code example creates several pairs of TimeSpan objects and calculatestheir difference with the Subtract method. See Example TimeSpan Subtract and AddMethodsTimeSpan.ToString ( String ) MethodReturns the string representation of the value of this instance.returnValue = instance.ToString( )A string that represents the value of this instance.The return value is of the form: [-][d.]hh:mm:ss[.ff] Items in square brackets([ and ]) are optional, colons and periods (: and.) are literal characters;and the other items are as follows.Item Descriptionws optional white space"-" optional minus sign indicating a negative TimeSpand days, ranging from 0 to 10675199hh hours, ranging from 0 to 23mm minutes, ranging from 0 to 59ss optional seconds, ranging from 0 to 59ff optional fractional seconds, consisting of 1 to 7 decimal digitsFor more information about comparing the string representation of TimeSpan andOracle data types, see article Q324577, "System.TimeSpan Does Not Match Oracle 9iINTERVAL DAY TO SECOND Data Type," in the Microsoft Knowledge Base athttp://support.microsoft.com.The return value of this method can be consumed by Parse.TimeSpan.TryParse ( String, TimeSpan ) MethodConstructs a new TimeSpan object from a time interval specified in a string. Parameters
  • 137. Chapter 14 Scripting Quicktest Professional Page 137Dani Vainstein DotNetFactory Page 137 of 151specify the time interval and the variable where the new TimeSpan object is returned.returnValue = instance.TryParse( s, Byref result )Parameter Descriptions A string that specifies a time interval.resultWhen this method returns, contains an object that represents the timeinterval specified by s, or Zero if the conversion failed. This parameter ispassed uninitialized.true if s was converted successfully; otherwise, false. This operation returns false ifthe s parameter is a null reference (Nothing in Visual Basic), has an invalidformat,represents a time interval less than MinValue or greater than MaxValue, or hasat least one days, hours, minutes, or seconds component outside its valid range.The TryParse method is like the TimeSpan.Parse method, except the TryParse methoddoes 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 TryParsemethod does not throw an exception if the conversion fails.Items in square brackets ([ and ]) are optional. One selection from the list of alternativesenclosed in braces ({ and }) and separated by vertical bars (|) is required. Colons andperiods (: and .) are literal characters and required. Other items are as follows.Item Descriptionws optional white space"-" optional minus sign indicating a negative TimeSpand days, ranging from 0 to 10675199hh hours, ranging from 0 to 23mm minutes, ranging from 0 to 59ss optional seconds, ranging from 0 to 59ff optional fractional seconds, consisting of 1 to 7 decimal digitsThe components of s must collectively specify a time interval greater than or equal toMinValue and less than or equal to MaxValue.DotNetFactory TasksWorld CalendarsThe Following code displays the different world calendars using the DOT.NET Calendarsobjects, CultutreInfo and more.Notice to the usage of the dictionary; the dictionary holds a class for every entry.
  • 138. Chapter 14 Scripting Quicktest Professional Page 138Dani Vainstein DotNetFactory Page 138 of 151Option ExplicitConst CULTURE_INFO = "System.Globalization.CultureInfo"Dim calendarsArr, cultureArr, todayDim nCal, calNameDim nDay, nMonth, nYearDim calDictClass CalendarInfoPrivate m_calendar, m_culturePrivate m_ciName, m_calName ** Class private eventsPrivate Sub Class_Initialize()Set m_calendar = Nothing : Set m_culture = NothingEnd SubPrivate Sub Class_Terminate()Set m_calendar = Nothing : Set m_culture = NothingEnd Sub ** System.Globalization.CultureInfoPublic Property Get CultureInfo()Set CultureInfo = m_cultureEnd Property ** System.Globalization.CalendarPublic Property Get Calendar()Set Calendar = m_calendarEnd PropertyPublic Property Let CalendarName( ByVal value )m_calName = valueSet m_calendar = DotNetFactory.CreateInstance( _"System.Globalization." & m_calName )End PropertyPublic Property Get CalendarName()CalendarName = m_calNameEnd PropertyPublic Property Let CultureName( ByVal value )m_ciName = valueSet m_culture = DotNetFactory.CreateInstance( _CULTURE_INFO, "System", m_ciName, True )Set m_culture.DateTimeFormat.Calendar = m_calendarEnd PropertyPublic Property Get CultureName()CultureName = m_ciNameEnd PropertyPublic Function GetMonthNames( ByVal nYear )Dim i, outStrFor i = 1 To m_calendar.GetMonthsInYear( nYear ) - 1outStr = outStr & _m_culture.DateTimeFormat.MonthNames.GetValue( CInt( i ) ) & ", "NextGetMonthNames = outStrEnd FunctionPublic Function GetAbbrMonthNames( ByVal nYear )Dim i, outStr
  • 139. Chapter 14 Scripting Quicktest Professional Page 139Dani Vainstein DotNetFactory Page 139 of 151For i = 1 To m_calendar.GetMonthsInYear( nYear ) - 1outStr = outStr & _m_culture.DateTimeFormat.AbbreviatedMonthNames.GetValue( CInt( i ) ) & ", "NextGetAbbrMonthNames = outStrEnd FunctionPublic Function GetDaysInMonth( ByVal nYear )Dim i, outStrFor i = 1 To m_calendar.GetMonthsInYear( nYear )outStr = outStr & m_calendar.GetDaysInMonth( nYear, Clng( i ) ) & ", "NextGetDaysInMonth = outStrEnd FunctionEnd ClassSet today = DotNetFactory.CreateInstance( "System.DateTime" ).TodaySet calDict = CreateObject( "Scripting.Dictionary" )calendarsArr = Array( "GregorianCalendar", "HebrewCalendar", "HijriCalendar", _"JapaneseCalendar", "KoreanCalendar", "TaiwanCalendar", _"PersianCalendar", "ThaiBuddhistCalendar", "JulianCalendar", _"KoreanLunisolarCalendar", "UmAlQuraCalendar" )cultureArr = Array ( "en-US", "he-IL", "ar-SA", "ja-JP", "ko-KR", "zh-TW", _vbNullString, vbNullString, vbNullString, vbNullString, _vbNullString ) ** Building dictionaryFor nCal = LBound( calendarsArr ) To UBound( calendarsArr )calName = calendarsArr( nCal )calDict.Add calendarsArr( nCal ), New CalendarInfocalDict( calName ).CalendarName = calName ** Not all calendars are supported by cultureInfoIf StrComp( cultureArr( nCal ), vbNullString ) <> 0 ThencalDict( calName ).CultureName = cultureArr( nCal )End IfnYear = Clng( calDict( calName ).Calendar.GetYear( today ) )Print calDict( calName ).Calendar.GetType() & " Current Year : " & nYearPrint "Algorithm Type: " & calDict( calName ).Calendar.AlgorithmTypePrint "MonthsInYear: " & calDict(calName).Calendar.GetMonthsInYear( Clng( nYear ) )Print "DaysInYear: " & calDict( calName ).Calendar.GetDaysInYear( Clng( nYear ) )Print "GetDaysInMonth: "Print calDict( calName ).GetDaysInMonth( nYear )If Not calDict( calName ).CultureInfo Is Nothing ThenPrint "NativeCalendarName: " & _calDict( calName ).CultureInfo.DateTimeFormat.NativeCalendarNamePrint "MonthNames: " & calDict( calName ).GetMonthNames( nYear )Print "AbbreviatedMonthNames: " & calDict(calName).GetAbbrMonthNames(nYear)End IfnMonth = calDict( calName ).Calendar.GetMonth( today )nDay = calDict( calName ).Calendar.GetDayOfMonth( today )Print "IsLeapDay: " & calDict( calName ).Calendar.IsLeapDay( _nYear , Clng( nMonth ), Clng( nDay ) )Print "IsLeapMonth: " & _calDict( calName ).Calendar.IsLeapMonth( nYear, Clng( nMonth ) )
  • 140. Chapter 14 Scripting Quicktest Professional Page 140Dani Vainstein DotNetFactory Page 140 of 151Print "IsLeapYear: " & calDict( calName ).Calendar.IsLeapYear( nYear )Print String( 70, "=" )NextSet today = Nothing : Set calDict = NothingSystem.Collections.ArrayListOption ExplicitDim ArrayList, i, nItemPrivate Sub PrintArray( ByRef arrayList, ByVal msg )Dim outStr, Enumerator
  • 141. Chapter 14 Scripting Quicktest Professional Page 141Dani Vainstein DotNetFactory Page 141 of 151Set Enumerator = arrayList.GetEnumerator()Do While Enumerator.MoveNext()outStr = outStr & ", " & Enumerator.Current.ToString()LoopoutStr = Mid( outStr, 2 )Print msg & " ---> " & outStrSet Enumerator = NothingEnd SubSet ArrayList = DotNetFactory.CreateInstance( "System.Collections.ArrayList",, 15 )For i = 1 To 10nItem = RandomNumber( 1, 100 )ArrayList.Add nItemNextPrint "ArrayList.ToString : " & ArrayList.ToStringPrint "Array Properties"Print String( 18, "*" )Print "ArrayList.Count : " & ArrayList.CountPrint "ArrayList.Capacity : " & ArrayList.CapacityPrint "ArrayList.IsFixedSize : " & ArrayList.IsFixedSizePrint "ArrayList.IsReadOnly : " & ArrayList.IsReadOnlyPrint "ArrayList.IsSynchronized : " & ArrayList.IsSynchronizedCall PrintArray( ArrayList, "Random Array" )ArrayList.SortCall PrintArray( ArrayList, "Sorted Array" )Print "Contains 33? ---> " & ArrayList.Contains( 33 )Print "Contains " & nItem & "? ---> " & ArrayList.Contains( nItem )Print "IndexOf " & nItem & " ---> " & ArrayList.IndexOf( nItem )ArrayList.Add 11Call PrintArray( ArrayList, "After added 11" )ArrayList.RemoveAt 3Call PrintArray( ArrayList, "After removed index 3" )ArrayList.TrimToSizePrint "After TrimToSize, ArrayList.Capacity : " & ArrayList.CapacityArrayList.ReverseCall PrintArray( ArrayList, "Reverse Array" )Set ArrayList = NothingCallChain using System.Collections.StackIn WinRunner the feature Call Chain gave the developer the capability to track functioncalling in the program flow. Every moment you could see wich function was called byanother function. This can help a lot, when debugging complex scripts. Unfortunately QTPdoes not support this great built-in mechanism ( till version 9.2 ). Alternatively you canbuild and handle a CallChain of your own using a stack ( the same method is used by theoperating system )Option ExplicitDim CallChain Can be used as a Global variableSet CallChain = DotNetFactory.CreateInstance( "System.Collections.Stack" )Private Function Func1()CallChain.Push( Environment( "ActionName" ) & "::Func1" )
  • 142. Chapter 14 Scripting Quicktest Professional Page 142Dani Vainstein DotNetFactory Page 142 of 151Call Func2()Call Sub3()CallChain.PopEnd FunctionPrivate Function Func2()CallChain.Push( Environment( "ActionName" ) & "::Func2" )Call Func4()CallChain.PopEnd FunctionPrivate Sub Sub3()CallChain.Push( Environment( "ActionName" ) & "::Sub3") ** Do SomethingCallChain.PopEnd SubPrivate Function Func4()CallChain.Push( Environment( "ActionName" ) & "::Func4" ) ** Do SomethingCallChain.PopEnd FunctionPublic Sub ReportCallChain( ByVal saveToFile )Dim ie, clone, dtStrSet ie = Createobject( "InternetExplorer.Application" )ie.Visible = 1Do While ie.BusyWait 0, 500ie.StatusText = "Waiting for Report..."Loopie.Navigate "about:blank"ie.ToolBar = 0 : ie.AddressBar= 0 : ie.StatusBar = 0 : ie.MenuBar = 0ie.Width = 500 : ie.Height = 600 : ie.Left = 0 : ie.Top = 0dtStr = DotNetFactory.CreateInstance( "System.DateTime" ).Now.ToString( "F" )With ie.document.Writeln "<H1 align=left><u>Call Chain Report</u></H1>".Writeln "<H3 align=left>" & dtStr & "</H3>".Writeln "<html><head><title>Service Status</title></head>".Writeln "<body bgcolor=ivory>".Writeln "<table width=100%>".Writeln "<tr><td width=50%><b>Function call stack:</b></td></tr>"Set clone = CallChain.CloneDo While clone.Count > 0.Writeln "</tr><td width=50%>" & clone.Pop() & "</td></tr>"LoopSet clone = Nothing.Writeln "</table></body></html>" : .Write()If IsEmpty( saveToFile ) Then Exit Sub.execCommand "saveas", True, saveToFileEnd WithEnd Sub ** Script Starts ...Call Func1()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
  • 143. Chapter 14 Scripting Quicktest Professional Page 143Dani Vainstein DotNetFactory Page 143 of 151Command Tab and Type ReportCallChain EmptyThen press enter and see what happens...Try again Typing ReportCallChain "C:MyReport.html"You can add the ReportCallChain function to an associated library.
  • 144. Chapter 14 Scripting Quicktest Professional Page 144Dani Vainstein DotNetFactory Page 144 of 151VisualBasic FunctionsOption ExplicitDim Dim vbi, vbsDim responsePrint "Format Function"Set vbs = DotNetFactory.CreateInstance( "Microsoft.VisualBasic.Strings" )Print "##,##0.00 ---> " & vbs.Format( 5459.4, "##,##0.00" )Print "###0.00 ---> " & vbs.Format( 334.9, "###0.00" )Print "0.00% ---> " & vbs.Format( 5, "0.00%" )Print "$#,##0;;Zero ---> " & vbs.Format( 0, "$#,##0;;Zero" )Print "$#,##0;;Zero ---> " & vbs.Format( 1, "$#,##0;;Zero" )Print "$#,##0;;Zero ---> " & vbs.Format( -1, "$#,##0;;Zero" )Print "$#,##0;($#,##0) ---> " & vbs.Format( 1000, "$#,##0;($#,##0)" )Print "$#,##0;($#,##0) ---> " & vbs.Format( -500, "$#,##0;($#,##0)" )Print "0" & vbs.Format( 5, "0" )Print "0" & vbs.Format( 0.5, "0" )Print "0.00" & vbs.Format( 5, "0.00" )Print "0.00" & vbs.Format( 0.5, "0.00" )Print "0.00E+00 ---> " & vbs.Format( 5, "0.00E+00" )Print "0.00E+00 ---> " & vbs.Format( 0.5, "0.00E+00")Print "0.00E+00 ---> " & vbs.Format( -5, "0.00E+00" )Print "0.00E-00 ---> " & vbs.Format( 5, "0.00E-00")Print "0.00E-00 ---> " & vbs.Format( 0.5, "0.00E-00" )Print "0.00E-00 ---> " & vbs.Format( -5, "0.00E-00" )Print "Yes/No ---> " & vbs.Format( True, "Yes/No" )Print "On/Off ---> " & vbs.Format( False, "On/Off" )Print "X ---> " & vbs.Format( 567346, "X" )Print "x ---> " & vbs.Format( 567346, "x" )Print "#e+# ---> " & vbs.Format( 12345678, "#e+#" )Print "; ---> " & vbs.Format( -1, ";" )Print "g ---> " & vbs.Format( 0.324532, "g" )Print "G ---> " & vbs.Format( 32453.2, "G" )Print "F ---> " & vbs.Format( 0.324532, "F" )Print "P ---> " & vbs.Format( 0.324532, "P" )Print "N ---> " & vbs.Format( 3984569, "N" )Print "E ---> " & vbs.Format( 0.324532, "E" )Print "C ---> " & vbs.Format( 324532, "C" )Print "G ---> " & vbs.Format( Now, "G" )Print "D ---> " & vbs.Format( Now, "D" )Print "T ---> " & vbs.Format( Now, "T" )Print "F ---> " & vbs.Format( Now, "F" )Print "M ---> " & vbs.Format( Now, "M" )Print "R ---> " & vbs.Format( Now, "R" )Print "U ---> " & vbs.Format( Now, "U" )Print "Y ---> " & vbs.Format( Now, "Y" )Print "zzz ---> " & vbs.Format( Now, "zzz" )Print String( 50, "*" ) & vbCrLf & "IIf Function"Set vbi = DotNetFactory.CreateInstance( "Microsoft.VisualBasic.Interaction" )response = Msgbox( "Do you like QTP?", vbYesNo + vbQuestion, "DotNetFactory" )Print vbi.IIf( response = vbYes, "You Pressed Yes", "You Pressed No" )
  • 145. Chapter 14 Scripting Quicktest Professional Page 145Dani Vainstein DotNetFactory Page 145 of 151Appendix 14.A – EnumerationsSystem.DateTimeKind EnumerationConstant Value DescriptionLocal 2 The time represented is local time.Unspecified 0 The time represented is not specified as either local time or CoordinatedUniversal Time (UTC).Utc 1 The time represented is UTC.Table 1 – DateTimeKind Enumeration Valueshttp://msdn2.microsoft.com/en-us/library/shx7s921.aspxSystem.DayOfWeek EnumerationConstant Val DescriptionFriday 5 Indicates Friday.Monday 1 Indicates Monday.Saturday 6 Indicates Saturday.Sunday 0 Indicates Sunday.Thursday 4 Indicates Thursday.Tuesday 2 Indicates Tuesday.Wednesday 3 Indicates Wednesday.Table 2 – DayOfWeek Enumeration ValuesStandard DateTime Format StringsFormat Name Descriptiond Short datepatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.ShortDatePattern property.D Long DatePatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.LongDatePattern property.f Fulldate/timepattern(short time)Represents a combination of the long date (D) and short time (t)patterns, separated by a space.F Fulldate/timepattern (longtime)Represents a custom DateTime format string defined by the currentDatetimeFormatInfo.FullDateTimePattern property.g Generaldate/timepattern(short time)Represents a combination of the short date (d) and short time (t)patterns, separated by a space.G Generaldate/timepattern (longtime)Represents a combination of the short date (d) and long time (T)patterns, separated by a space.
  • 146. Chapter 14 Scripting Quicktest Professional Page 146Dani Vainstein DotNetFactory Page 146 of 151M or m Month DayPatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.MonthDayPattern property.o Round-tripdate/timepatternRepresents a custom DateTime format string using a pattern thatpreserves time zone information. The pattern is designed to round-tripDateTime formats, including the Kind property, in text. Then theformatted string can be parsed back using Parse or ParseExact withthe correct Kind property value.R or r RFC1123patternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.RFC1123Pattern property. The pattern is a definedstandard and the property is read-only. Therefore, it is always the sameregardless of the culture used or the format provider supplied.s Sortabledate/timepattern;conforms toISO 8601Represents a custom DateTime format string defined by the currentDatetimeFormatInfo.SortableDateTimePattern property. This pattern isa defined standard and the property is read-only. Therefore, it is alwaysthe same regardless of the culture used or the format providersupplied.t Short timepatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.ShortTimePattern property.T Long timepatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.LongTimePattern property.u Universalsortabledate/timepatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.UniversalSortableDateTimePattern property. Thispattern is a defined standard and the property is read-only. Therefore,it is always the same regardless of the culture used or the formatprovider supplied.U Universalsortabledate/timepatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.FullDateTimePattern property.This pattern is the same as the full date/long time (F) pattern.However, formatting operates on the Coordinated Universal Time (UTC)that is equivalent to the DateTime object being formatted.Y or y Year monthpatternRepresents a custom DateTime format string defined by the currentDatetimeFormatInfo.YearMonthPattern propertyTable 3 – DateTime Format Stringshttp://msdn2.microsoft.com/en-us/library/az4se3k1.aspxCustom DateTime Format StringsFomat Descriptiond Represents the day of the month as a number from 1 through 31. Asingle-digit day is formatted without a leading zero. For moreinformation about using a single format specifier, see Using SingleCustom Format Specifiers.dd Represents the day of the month as a number from 01 through 31. Asingle-digit day is formatted with a leading zero.ddd Represents the abbreviated name of the day of the week as defined inthe currentSystem.Globalization.DateTimeFormatInfo.AbbreviatedDayNamesproperty.dddd (plus any numberof additional "d"specifiers)Represents the full name of the day of the week as defined in thecurrent System.Globalization.DateTimeFormatInfo.DayNames property.f Represents the most significant digit of the seconds fraction.
  • 147. Chapter 14 Scripting Quicktest Professional Page 147Dani Vainstein DotNetFactory Page 147 of 151Note that if the "f" format specifier is used alone, without other formatspecifiers, it is interpreted as the "f" standard DateTime format specifier(full date/time pattern). For more information about using a singleformat specifier, see Using Single Custom Format Specifiers.When you use this format specifier with the ParseExact or TryParseExactmethod, the number of "f" format specifiers that you use indicates thenumber 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 isdisplayed if the digit is zero. For more information about using a singleformat specifier, see Using Single Custom Format Specifiers.When you use this format specifier with the ParseExact orTryParseExact method, the number of "F" format specifiers that youuse indicates the maximum number of most significant digits of theseconds fraction to parse.FF Represents the two most significant digits of the seconds fraction.However, trailing zeros, or two zero digits, are not displayed.FFF Represents the three most significant digits of the seconds fraction.However, trailing zeros, or three zero digits, are not displayed.FFFF Represents the four most significant digits of the seconds fraction.However, trailing zeros, or three zero digits, are not displayed.FFFFF Represents the five most significant digits of the seconds fraction.However, trailing zeros, or three zero digits, are not displayed.FFFFFF Represents the six most significant digits of the seconds fraction.However, trailing zeros, or three zero digits, are not displayed.FFFFFFF Represents the seven most significant digits of the seconds fraction.However, trailing zeros, or three zero digits, are not displayed.g or gg (plus anynumber of additional"g" specifiers)Represents the period or era (A.D. for example). This specifier is ignoredif the date to be formatted does not have an associated period or erastring. For more information about using a single format specifier, seeUsing Single Custom Format Specifiers.h Represents the hour as a number from 1 through 12, that is, the houras represented by a 12-hour clock that counts the whole hours sincemidnight or noon. Consequently, a particular hour after midnight isindistinguishable from the same hour after noon. The hour is notrounded, and a single-digit hour is formatted without a leading zero. Forexample, given a time of 5:43, this format specifier displays "5". Formore information about using a single format specifier, see Using SingleCustom Format Specifiers.hh, hh (plus anynumber of additional"h" specifiers)Represents the hour as a number from 01 through 12, that is, the houras represented by a 12-hour clock that counts the whole hours sincemidnight or noon. Consequently, a particular hour after midnight isindistinguishable from the same hour after noon. The hour is not
  • 148. Chapter 14 Scripting Quicktest Professional Page 148Dani Vainstein DotNetFactory Page 148 of 151rounded, and a single-digit hour is formatted with a leading zero. Forexample, given a time of 5:43, this format specifier displays "05".H Represents the hour as a number from 0 through 23, that is, the houras represented by a zero-based 24-hour clock that counts the hourssince midnight. A single-digit hour is formatted without a leading zero.HH, HH (plus anynumber of additional"H" specifiers)Represents the hour as a number from 00 through 23, that is, the houras represented by a zero-based 24-hour clock that counts the hourssince midnight. A single-digit hour is formatted with a leading zero.K Represents different values of the DateTime.Kind property, that is,Local, Utc, or Unspecified. This specifier round-trips the kind value intext and preserves the time zone. For the Local kind value, this specifieris equivalent to the "zzz" specifier and displays the local offset, forexample, "-07:00". For the Utc kind value, the specifier displays a "Z"character to represent a UTC date. For the Unspecified kind value, thespecifier is equivalent to "" (nothing).m Represents the minute as a number from 0 through 59. The minuterepresents whole minutes passed since the last hour. A single-digitminute is formatted without a leading zero. For more information aboutusing a single format specifier, see Using Single Custom FormatSpecifiers.mm, mm (plus anynumber of additional"m" specifiers)Represents the minute as a number from 00 through 59. The minuterepresents whole minutes passed since the last hour. A single-digitminute is formatted with a leading zero.M Represents the month as a number from 1 through 12. A single-digitmonth is formatted without a leading zero. For more information aboutusing a single format specifier, see Using Single Custom FormatSpecifiers.MM Represents the month as a number from 01 through 12. A single-digitmonth is formatted with a leading zero.MMM Represents the abbreviated name of the month as defined in the currentSystem.Globalization.DateTimeFormatInfo.AbbreviatedMonthNamespropertyMMMM Represents the full name of the month as defined in the currentSystem.Globalization.DateTimeFormatInfo.MonthNames property.s Represents the seconds as a number from 0 through 59. The secondrepresents whole seconds passed since the last minute. A single-digitsecond is formatted without a leading zero. For more information aboutusing a single format specifier, Using Single Custom Format Specifiers.ss, ss (plus any numberof additional "s"specifiers)Represents the seconds as a number from 00 through 59. The secondrepresents whole seconds passed since the last minute. A single-digitsecond is formatted with a leading zero.t Represents the first character of the A.M./P.M. designator defined in thecurrent System.Globalization.DateTimeFormatInfo.AMDesignator orSystem.Globalization.DateTimeFormatInfo.PMDesignator property. TheA.M. designator is used if the hour in the time being formatted is lessthan 12; otherwise, the P.M. designator is used. For more informationabout using a single format specifier, see Using Single Custom FormatSpecifiers.tt, tt (plus any numberof additional "t"specifiers)Represents the A.M./P.M. designator as defined in the currentSystem.Globalization.DateTimeFormatInfo.AMDesignator orSystem.Globalization.DateTimeFormatInfo.PMDesignatorproperty. The A.M. designator is used if the hour in the time beingformatted is less than 12; otherwise, the P.M. designator is used.
  • 149. Chapter 14 Scripting Quicktest Professional Page 149Dani Vainstein DotNetFactory Page 149 of 151y Represents the year as at most a two-digit number. If the year hasmore than two digits, only the two low-order digits appear in the result.If the year has fewer than two digits, the number is formatted without aleading zero. For more information about using a single format specifier,see Using Single Custom Format Specifiers.yy Represents the year as a two-digit number. If the year has more thantwo digits, only the two low-order digits appear in the result. If the yearhas fewer than two digits, the number is padded with leading zeroes toachieve two digits.yyy Represents the year as a three-digit number. If the year has more thanthree digits, only the three low-order digits appear in the result. If theyear has fewer than three digits, the number is padded with leadingzeroes to achieve three digits.Note that for the Thai Buddhist calendar, which can have five-digityears, this format specifier displays all five digits.yyyy Represents the year as a four-digit number. If the year has more thanfour digits, only the four low-order digits appear in the result. If the yearhas fewer than four digits, the number is padded with leading zeroes toachieve four digits.Note that for the Thai Buddhist calendar, which can have five-digityears, this format specifier renders all five digitsyyyyy (plus anynumber of additional"y" specifiers)Represents the year as a five-digit number. If the year has more thanfive digits, only the five low-order digits appear in the result. If the yearhas fewer than five digits, the number is padded with leading zeroes toachieve five digits.If there are additional "y" specifiers, the number is padded with as manyleading zeroes as necessary to achieve the number of "y" specifiers.z Represents the signed time zone offset of your system from GreenwichMean Time (GMT) measured in hours. For example, the offset for acomputer 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 hoursbehind GMT. The offset ranges from –12 through +13. A single-digitoffset is formatted without a leading zero. The offset is affected bydaylight savings time. For more information about using a single formatspecifier, see Using Single Custom Format Specifiers.zz Represents the signed time zone offset of your system from GreenwichMean Time (GMT) measured in hours. For example, the offset for acomputer 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 hoursbehind GMT. The offset ranges from –12 through +13. A single-digitoffset is formatted with a leading zero. The offset is affected by daylightsavings time.zzz, zzz (plus anynumber of additional"z" specifiers)Represents the signed time zone offset of your system from GreenwichMean Time (GMT) measured in hours and minutes. For example, theoffset for a computer in the Pacific Standard Time zone is "-08:00".The offset is always displayed with a leading sign. A plus sign (+)
  • 150. Chapter 14 Scripting Quicktest Professional Page 150Dani Vainstein DotNetFactory Page 150 of 151indicates hours ahead of GMT and a minus sign (-) indicates hoursbehind GMT. The offset ranges from –12 through +13. A single-digitoffset is formatted with a leading zero. The offset is affected by daylightsavings time.: The time separator defined in the currentSystem.Globalization.DateTimeFormatInfo.TimeSeparator property thatis used to differentiate hours, minutes, and seconds./ The date separator defined in the currentSystem.Globalization.DateTimeFormatInfo.DateSeparator property thatis used to differentiate years, months, and days." Quoted string (quotation mark). Displays the literal value of any stringbetween two quotation marks ("). Precede each quotation mark with anescape character (). Quoted string (apostrophe). Displays the literal value of any stringbetween two apostrophe () characters.%c Represents the result associated with a custom format specifier "c",when the custom DateTime format string consists solely of that customformat 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 moreinformation about using a single format specifier, see Using SingleCustom Format Specifiers.c The escape character. Displays the character "c" as a literal when thatcharacter is preceded by the escape character (). To insert thebackslash 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 affectformatting.Table 4 – Custom DatTime Format Stringshttp://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspxSystem.Globalization.DateTimeStyles EnumerationMember Value DescriptionAdjustToUniversal 16Indicates that the date and time will be returned as aCoordinated Universal Time (UTC).AllowInnerWhite 4Indicates that extra white-space characters in themiddle of the string must be ignored during parsing,except if those white-space characters occur in theDateTimeFormatInfo format patterns.AllowLeadingWhite 1Indicates that leading white-space characters must beignored during parsing, except if those white-spacecharacters occur in the DateTimeFormatInfo formatpatterns.AllowTrailingWhite 2Indicates that trailing white-space characters must beignored during parsing, except if those white-spacecharacters occur in the DateTimeFormatInfo formatpatterns.AllowWhiteSpaces 7Indicates that extra white-space characters anywherein the string must be ignored during parsing, except ifthose white-space characters occur in theDateTimeFormatInfo format patterns. This value is acombination of the AllowLeadingWhite,AllowTrailingWhite, and AllowInnerWhite values.
  • 151. Chapter 14 Scripting Quicktest Professional Page 151Dani Vainstein DotNetFactory Page 151 of 151AssumeLocal 32Indicates that if no time zone is specified in the parsedstring, the string is assumed to denote a local time.Cannot be used with AssumeUniversal orRoundtripKind.AssumeUniversal 64Indicates that if no time zone is specified in the parsedstring, the string is assumed to denote a CoordinatedUniversal Time (UTC). Cannot be used withAssumeLocal or RoundtripKind.NoCurrentDateDefault 8Indicates that, if the parsed string contains only thetime and not the date, the DateTime.Parse andDateTime.ParseExact methods assume the Gregoriandate with year = 1, month = 1, and day = 1. If thisvalue is not used, the current date is assumed.None 0Indicates that the default formatting options must beused. This is the default style for DateTime.Parse,DateTime.ParseExact, and DateTime.TryParse.RoundtripKind 128Preserves the DateTimeKind field of a date when aDateTime object is converted to a string and the stringis then converted back to a DateTime object.Table 5 – System.Globalization.DateTimeStyles Enumeration

×