Professional Documents
Culture Documents
Scripting QTP - CH14 - Dot Net Factory
Scripting QTP - CH14 - Dot Net Factory
Page 1
DOTNETFACTORY .................................................................................................................... 4 THE DOTNETFACTORY OBJECT................................................................................................ 4 CREATEINSTANCE METHOD .................................................................................................. 4 QTP DOTNETFACTORY ............................................................................................................. 5 SYSTEM.DATETIME STRUCTURE ............................................................................................... 9 SYSTEM.DATETIME FIELDS................................................................................................... 9 DateTime.MaxValue Field............................................................................................ 10 DateTime.MinValue Field ............................................................................................ 10 SYSTEM.DATETIME CONTRUCTORS .................................................................................... 10 DateTime.DateTime( int64 ) Constructor ..................................................................... 11 DateTime.DateTime ( int64, DateTimeKind ) Constructor .......................................... 12 DateTime.DateTime(Int32, Int32, Int32) Constructor .................................................. 14 DateTime.DateTime(Int32, Int32, Int32, Calendar) Constructor.................................. 15 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32) Constructor................... 16 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar ) Constructor . 17 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind ) Constructor.................................................................................................................... 19 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32 ) Constructor ....... 20 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar ) Constructor.................................................................................................................... 20 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind ) Constructor.................................................................................................................... 21 DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind ) Constructor......................................................................................... 22 DATETIME PROPERTIES ....................................................................................................... 23 DateTime.Date Property ............................................................................................... 24 DateTime.Day Property ................................................................................................ 25 DateTime.DayOfWeek Property................................................................................... 25 DateTime.DayOfYear Property .................................................................................... 26 DateTime.Hour Property............................................................................................... 27 DateTime.Kind Property ............................................................................................... 27 DateTime.Millisecond Property .................................................................................... 29 DateTime.Minute Property ........................................................................................... 29 DateTime.Month Property ............................................................................................ 29 DateTime.Now Property ............................................................................................... 29 DateTime.Second Property ........................................................................................... 30 DateTime.Ticks Property .............................................................................................. 30 DateTime.TimeOfDay Property.................................................................................... 30 DateTime.Today Property............................................................................................. 31 DateTime.UtcNow Property ......................................................................................... 31 DateTime.Year Property ............................................................................................... 32 DATETIME METHODS .......................................................................................................... 32 DateTime.Add ( TimeSpan ) Method ........................................................................... 34 DateTime.AddDays ( Double ) Method........................................................................ 35 DateTime.AddHours ( Double ) Method ...................................................................... 36 DateTime.AddMilliseconds ( Double ) Method ........................................................... 36 DateTime.AddMinutes ( Double ) Method ................................................................... 37 DateTime.AddMonths ( Integer ) Method .................................................................... 37
Dani Vainstein DotNetFactory Page 1 of 151
Chapter 14
Page 2
DateTime.AddSeconds ( Double ) Method................................................................... 38 DateTime.AddTicks ( Long ) Method .......................................................................... 39 DateTime.AddYears ( Integer ) Method ....................................................................... 39 DateTime.Compare ( DateTime, DateTime ) Method .................................................. 40 DateTime.CompareTo ( DateTime ) Method................................................................ 40 DateTime.DaysInMonth ( Integer, Integer ) Method .................................................... 41 DateTime.Equals ( DateTime ) Method........................................................................ 45 DateTime.Equals ( DateTime, DateTime ) Method ...................................................... 45 DateTime.FromBinary ( Long ) Method....................................................................... 46 DateTime.FromFileTime ( Long ) Method ................................................................... 47 DateTime.FromFileTimeUtc ( Long ) Method ............................................................. 48 DateTime.GetTimeFormats Method ............................................................................. 49 DateTime.GetTimeFormats () Method ......................................................................... 49 DateTime.GetTimeFormats ( Char ) Method................................................................ 50 DateTime.GetTimeFormats ( IFormatProvider ) Method............................................. 51 DateTime.GetTimeFormats ( Char, IFormatProvider ) Method ................................... 53 DateTime.GetHashCode () Method .............................................................................. 54 DateTime.GetTypeCode () Method .............................................................................. 55 DateTime.IsDaylightSavingTime () Method ................................................................ 55 DateTime.IsLeapYear ( Integer ) Method..................................................................... 56 DateTime.op_Addition ( DateTime, TimeSpan ) Method ............................................ 56 DateTime.op_Equality ( DateTime, DateTime ) Method ............................................. 57 DateTime.op_GreaterThan ( DateTime, DateTime ) Method....................................... 57 DateTime.op_GreaterThanOrEqual ( DateTime, DateTime ) Method ......................... 58 DateTime.op_Inequality ( DateTime, DateTime ) Method........................................... 58 DateTime.op_LessThan ( DateTime, DateTime ) Method ........................................... 59 DateTime.op_LessThanOrEqual ( DateTime, DateTime ) Method.............................. 59 DateTime.op_Subtraction Method ................................................................................ 59 DateTime.op_Subtraction ( DateTime, DateTime ) Method ........................................ 59 DateTime.op_Subtraction ( DateTime, TimeSpan ) Method ........................................ 61 DateTime.Parse Method................................................................................................ 61 DateTime.Parse ( String ) Method ................................................................................ 62 DateTime.Parse ( String, IFormatProvider ) Method.................................................... 63 DateTime.Parse ( String, IFormatProvider, DateTimeStyles ) Method ........................ 64 DateTime.ParseExact Method....................................................................................... 65 DateTime.ParseExact ( String, String, IFormatProvider ) Method............................... 66 DateTime.ParseExact ( String, String, IFormatProvider, DateTimeStyles ) Method ... 67 DateTime.ParseExact ( String, String[], IFormatProvider, DateTimeStyles ) Method. 68 DateTime.SpecifyKind ( DateTime, DateTimeKind ) Method..................................... 70 DateTime.Subtract Method ........................................................................................... 71 DateTime.Subtract ( DateTime ) Method ..................................................................... 71 DateTime.Subtract ( TimeSpan ) Method ..................................................................... 72 DateTime.ToFileTime () Method.................................................................................. 73 DateTime.ToFileTimeUtc () Method............................................................................ 74 DateTime.ToLocalTime () Method............................................................................... 74 DateTime.ToLongDateString () Method....................................................................... 75 DateTime.ToLongTimeString () Method...................................................................... 77 DateTime.ToShortDateString () Method ...................................................................... 77 DateTime.ToShortTimeString () Method ..................................................................... 78 DateTime.ToString Method .......................................................................................... 79 DateTime.ToString () Method ...................................................................................... 79
Dani Vainstein DotNetFactory Page 2 of 151
Chapter 14
Page 3
DateTime.ToString ( IFormatProvider ) Method.......................................................... 82 DateTime.ToString ( String ) Method........................................................................... 83 DateTime.ToString ( String, IFormatProvider ) Method .............................................. 85 DateTime.ToUniversalTime () Method ........................................................................ 86 DateTime.TryParse Method.......................................................................................... 86 DateTime.TryParse ( String, DateTime ) Method......................................................... 87 DateTime.TryParse ( String, IFormatProvider, DateTimeStyles, DateTime ) Method 88 DateTime.TryParseExact Method................................................................................. 89 DateTime.TryParse ( String, String, IFormatProvider, DateTimeStyles, DateTime ) Method .......................................................................................................................... 89 DateTime.TryParse ( String, String[], IFormatProvider, DateTimeStyles, DateTime ) Method .......................................................................................................................... 90 SYSTEM.TIMESPAN STRUCTURE ............................................................................................. 92 SYSTEM.TIMESPAN CONTRUCTORS .................................................................................... 92 DateTime.TimeSpan ( int64 ) Constructor.................................................................... 92 DateTime.TimeSpan ( int32, int32, int32 ) Constructor ............................................... 94 DateTime.TimeSpan ( int32, int32, int32, int32 ) Constructor ..................................... 95 DateTime.TimeSpan ( int32, int32, int32, int32, int32 ) Constructor........................... 96 SYSTEM.TIMESPAN FIELDS ................................................................................................. 98 TimeSpan.MaxValue Field ........................................................................................... 98 TimeSpan.MinValue Field............................................................................................ 99 TimeSpan.TicksPerDay Field ....................................................................................... 99 TimeSpan.TicksPerHour Field...................................................................................... 99 TimeSpan.TicksPerMillisecond Field......................................................................... 100 TimeSpan.TicksPerMinute Field ................................................................................ 100 TimeSpan.TicksPerSecond Field ................................................................................ 100 TimeSpan.Zero Field................................................................................................... 100 TIMESPAN PROPERTIES ..................................................................................................... 100 TimeSpan.Days Property ............................................................................................ 101 TimeSpan.Hours Property........................................................................................... 103 TimeSpan.Milliseconds Property ................................................................................ 104 TimeSpan.Minutes Property ....................................................................................... 104 TimeSpan.Seconds Property ....................................................................................... 105 TimeSpan.Ticks Property............................................................................................ 105 TimeSpan.TotalDays Property .................................................................................... 105 TimeSpan.TotalHours Property .................................................................................. 106 TimeSpan.TotalMilliseconds Property........................................................................ 106 TimeSpan.TotalMinutes Property ............................................................................... 107 TimeSpan.TotalSeconds Property............................................................................... 107 TIMESPAN METHODS ........................................................................................................ 107 TimeSpan.Add ( TimeSpan ) Method ......................................................................... 109 DateTime.Compare ( TimeSpan, TimeSpan ) Method ............................................... 110 TimeSpan.CompareTo ( TimeSpan ) Method............................................................. 112 TimeSpan.Duration ( ) Method ................................................................................... 113 TimeSpan.Equals Method ........................................................................................... 114 TimeSpan.Equals ( TimeSpan ) Method ..................................................................... 114 TimeSpan.Equals ( TimeSpan, TimeSpan ) Method................................................... 115 TimeSpan.FromDays ( Double ) Method.................................................................... 115 TimeSpan.FromHours ( Double ) Method .................................................................. 117 TimeSpan.FromMilliseconds ( Double ) Method ....................................................... 119 TimeSpan.FromMinutes ( Double ) Method............................................................... 121
Dani Vainstein DotNetFactory Page 3 of 151
Chapter 14
Page 4
TimeSpan.FromSeconds ( Double ) Method............................................................... 122 TimeSpan.FromTicks ( Long ) Method ...................................................................... 123 TimeSpan.GetHashCode ( ) Method........................................................................... 124 TimeSpan.Negate ( ) Method...................................................................................... 125 TimeSpan.op_Addition ( TimeSpan, TimeSpan ) Method ......................................... 126 TimeSpan.op_Equality ( TimeSpan, TimeSpan ) Method .......................................... 128 TimeSpan.op_GreaterThan ( TimeSpan, TimeSpan ) Method ................................... 130 TimeSpan.op_GreaterThanOrEqual ( TimeSpan, TimeSpan ) Method...................... 130 TimeSpan.op_Inequality ( TimeSpan, TimeSpan ) Method ....................................... 130 TimeSpan.op_LessThan ( TimeSpan, TimeSpan ) Method ........................................ 131 TimeSpan.op_LessThanOrEqual ( TimeSpan, TimeSpan ) Method .......................... 131 TimeSpan.op_Subtraction ( TimeSpan, TimeSpan ) Method ..................................... 132 TimeSpan.op_UnaryNegation ( ) Method................................................................... 132 TimeSpan.op_UnaryPlus ( ) Method .......................................................................... 133 TimeSpan.Parse ( String ) Method.............................................................................. 133 TimeSpan.Subtract ( TimeSpan ) Method................................................................... 135 TimeSpan.ToString ( String ) Method ........................................................................ 136 TimeSpan.TryParse ( String, TimeSpan ) Method...................................................... 136 DOTNETFACTORY TASKS ...................................................................................................... 137 WORLD CALENDARS ......................................................................................................... 137 SYSTEM.COLLECTIONS.ARRAYLIST ................................................................................. 140 CALLCHAIN USING SYSTEM.COLLECTIONS.STACK .......................................................... 141 APPENDIX 14.A ENUMERATIONS ........................................................................................ 144 System.DateTimeKind Enumeration .......................................................................... 145 System.DayOfWeek Enumeration .............................................................................. 145 Standard DateTime Format Strings............................................................................. 145 Custom DateTime Format Strings .............................................................................. 146 System.Globalization.DateTimeStyles Enumeration .................................................. 150
DotNetFactory
The DotNetFactory Object
Enables you to create an instance of a .NET object, and access its methods and properties.
You can use this object to access the static methods and properties of a class that does not have an instance constructor, for example, System.Environment, as well as a class that does.
CreateInstance Method
Dani Vainstein
DotNetFactory
Page 4 of 151
Chapter 14
Page 5
If you want to use a .NET object as an argument for a method in QuickTest, you must first create a COM interface for the .NET object using the CreateInstance method. Then you pass that interface as the method argument.
Parameter
TypeName
Description
The full name of the object type, for example, System.Windows.Forms.Form. Optional. If the assembly is preloaded in the registry, you do not need to enter it. Otherwise, you should enter the full path name, for example, System.Windows.Forms. If you want to create an instance of a type in the GAC (Global Assembly Cache), you can enter the short name, for example, Forms. Note: If you do not pass this argument, QuickTest assumes that the assembly is resident in memory. If QuickTest does not find the assembly, an error message is displayed during the run session.
Assembly
args
Optional. The required arguments, if any, for the specified TypeName and/or Assembly
QTP DotNetFactory
When QTP version 9.0 was released. I have noticed that a new utility object was added,the DotNetFactory object. Since, that period of time, I was working on a web application, I thought myself , that DotNetFactory is a utility to work with .NET applications, like the DOT.NET Extensibility In QTP Version 9.2, I so the following example in the QTP help
Set var_CreateInstance = _ DotNetFactory.CreateInstance("System.Windows.Forms.Form", "System.Windows.Forms") var_CreateInstance.Show wait 2 var_CreateInstance.Close
And also
Set var_CreateInstance = DotNetFactory.CreateInstance("System.Environment") msgbox var_CreateInstance.CurrentDirectory
The first example display an empty windows form. I started to think, why I need to display a form , during a test run. The second example catch my eye, and when I tried it in qtp, I got the following result :
Dani Vainstein
DotNetFactory
Page 5 of 151
Chapter 14
Page 6
"wow!!" I said to my self, nice to know that I can have every single environment value of the system, especially SystemDirectory property. The others values, can be retrieved using standard VBScript objects and QTP Environment object. So, again I did not paid attention and full research for the dot.net factory. One month later, I add an issue when testing a financial application. The application ( web based ) shows the interests to pay for each month. Because the application is a bank system application, I can't show screenshots. But a web table was displayed in the following format :
Date
Tue, 12 Sep 2006 Thu, 12 Oct 2006 Sun, 12 Nov 2006 Tue, 12 Dec 2006 Dani Vainstein
Amount
2500$ 2490$ 2475$ 2466$ DotNetFactory Page 6 of 151
Chapter 14
Page 7
2390$ 2285$
My problem here, were the dates. VBScript doesn't able to convert formats, to the specific format I needed, and beside this, any user can change the display format to : mm/dd/yyyy or mmddyy or dd\mm\yy etc.
dteDate = Cdate( "Tue, 12 Sep 2006" )
Because the CDate conversion error, in pure vbscript I need a function like the follows
Option Explicit Dim arr1, arr2, MyDate, nMonth, dteDate MyDate = Browser("B").Page("P").WebTable("rates").GetCellData(1,1) arr1 = Split( MyDate, "," ) arr2 = Split( arr1(1), " " ) Select Case arr2(2) Case "Jan" : nMonth = 1 Case "Feb" : nMonth = 2 Case "Mar" : nMonth = 3 Case "Apr" : nMonth = 4 Case "May" : nMonth = 5 Case "Jun" : nMonth = 6 Case "Jul" : nMonth = 7 Case "Aug" : nMonth = 8 Case "Sep" : nMonth = 9 Case "Oct" : nMonth = 10 Case "Nov" : nMonth = 11 Case "Dec" : nMonth = 12 End Select dteDate = DateSerial(arr2(3), nMonth, arr2(1)) msgbox dteDate
This process only to retrieve the first date, than, I have to use the DateAdd function, and another function to convert the new date, to the desired format. As you can see, this is a lot of work, beside, that the user can change the formats. Dani Vainstein DotNetFactory Page 7 of 151
Chapter 14
Page 8
The application has hundreds of date fields, and dates fields are very critical for the application. From this moment I start to make a research, to find a simplest and elegant solution. I found the System.DateTime object in the MSDN DOT.NET help, and remember immediately of the QTP example about the System.Environment object So I tried the follow :
Option Explicit Dim DateTime Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" )
A little more research, using the MSDN help I got the ultimate date handling functionality
Option Explicit Dim DateTime, SystemDateTime, i, Str Set SystemDateTime = DotNetFactory.CreateInstance( "System.DateTime" ) Set DateTime = SystemDateTime.Parse( "Tue, 12 Sep 2006" ) For i = 1 To 12
Dani Vainstein
DotNetFactory
Page 8 of 151
Chapter 14
Page 9
Str = Str & DateTime.AddMonths(i).ToString( "ddd, dd MMM yyyy" ) & vbNewLine Next Msgbox Str Set SystemDateTime = Nothing : Set DateTime = Nothing
So, the conclusion of all my research, is that you can use almost any DOT.NET object supported by your Dot.Net Framework ( today is version 3 ) , so this chapter of DotNetFactory will demonstrate only the System.DateTime and System.TimeSpan classes. In some examples I use The System.Text.TextBuilder class, System.Globalization.CultureInfo class, System.DateTimeKind Enumerator, System.Globalization.Calendar and more
System.DateTime Structure
Represents 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:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar. For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 midnight. A DateTime value is always 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.aspx
System.DateTime Fields
Name
MaxValue MinValue
Description
Represents the largest possible value of DateTime. This field is read-only. Represents the smallest possible value of DateTime. This field is read-only
Dani Vainstein
DotNetFactory
Page 9 of 151
Chapter 14
Page 10
DateTime.MaxValue Field
Represents the largest possible value of DateTime. This field is read-only
DateTime.MinValue Field
Represents the smallest possible value of DateTime. This field is read-only
The 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 Contructors
Initializes a new instance of the DateTime structure. Name
DateTime (Int64)
Description
Initializes a new instance of the DateTime structure to a specified number of ticks. Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time. Initializes a new instance of the DateTime structure to the specified year, month, and day. Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and Coordinated Universal Time (UTC) or local time. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar. Initializes a new instance of the DateTime structure DotNetFactory Page 10 of 151
DateTime (Int32, Int32, Int32) DateTime (Int32, Int32, Int32, Calendar) DateTime (Int32, Int32, Int32, Int32, Int32, Int32) DateTime (Int32, Int32, Int32, Int32, Int32, Int32, Calendar)
DateTime (Int32, Int32, Int32, Int32, Int32, Int32, Int32) DateTime (Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime (Int32, Int32, Int32, Dani Vainstein
Chapter 14
Page 11
to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
DateTime (Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind)
Parameter
ticks
Description
A date and time expressed in 100-nanosecond units.
System.DateTime object
Dani Vainstein
DotNetFactory
Page 11 of 151
Chapter 14
Page 12
).Ticks Set dtCustom = DotNetFactory.CreateInstance( "System.DateTime", , ticks ) ' ** Reporting Set SB = DotNetFactory.CreateInstance( "System.Text.StringBuilder" ) SB.AppendFormat format, 1, "maximum", dtMax, vbNewLine SB.AppendFormat format, 2, "minimum", dtMin, vbNewLine SB.AppendFormat format, 3, "custom", dtCustom, vbNewLine SB.AppendFormat "The custom datetime is created from {0:N0} ticks.", ticks Msgbox SB.ToString(), vbOkOnly, "DateTime( ticks )" ' ** Cleaning Set SB = Nothing : Set CI = Nothing Set dtCustom = Nothing : Set ticks = Nothing Set dtMin = Nothing : Set dtMax = Nothing : Set SDT = Nothing
Parameter
ticks kind
Description
A date and time expressed in 100-nanosecond units. One of the DateTimeKind values that indicates whether ticks specifies a local time, Coordinated Universal Time (UTC), or neither.
System.DateTime object
ArgumentOutOfRangeException - ticks is less than MinValue or greater than MaxValue. ArgumentException - Kind is not one of the DateTimeKind values.
The following code example uses the SpecifyKind method to demonstrate how the Kind property influences the ToLocalTime and ToUniversalTime conversion methods. Dani Vainstein DotNetFactory Page 12 of 151
Chapter 14
Page 13
Option Explicit Const DATE_PATTERN = "M/d/yyyy hh:mm:ss tt" Dim DateTime, saveNow, saveUtcNow, myDt Dim DateTimeKind Private Sub DisplayNow( ByVal title, ByRef inputDt ) Dim dtString dtString = inputDt.ToString( DATE_PATTERN ) Print title & " " & dtString & ", Kind = " & inputDt.Kind End Sub Public Sub Display( ByVal title, ByRef inputDt ) Dim dispDt, dtString Set 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 & vbNewLine End Sub 'Display Set 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 ' 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" ) expressed as UTC and
Dani Vainstein
DotNetFactory
Page 13 of 151
Chapter 14
Page 14
Set 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 = Nothing Set saveNow = Nothing : Set saveUtcNow = Nothing '
Parameter
year month day
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month).
System.DateTime object
Dani Vainstein
DotNetFactory
Page 14 of 151
Chapter 14
Page 15
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. ArgumentException - The specified parameters evaluate to less than MinValue or more than MaxValue.
The following code example uses the SpecifyKind method to demonstrate how the Kind property influences the ToLocalTime and ToUniversalTime conversion methods.
Option Explicit Dim DateTime Set DateTime = DotNetFactory.CreateInstance( "System.DateTime", ,1979, 7, 28) MsgBox DateTime.ToString() Set DateTime = Nothing
Parameter
year month Day calendar
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The Calendar that applies to this DateTime.
System.DateTime object
ArgumentNullException - calendar is a null reference (Nothing in Visual Basic). Dani Vainstein DotNetFactory Page 15 of 151
Chapter 14
Page 16
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. ArgumentException - The specified parameters evaluate to less than MinValue or more than MaxValue.
The time of day for the resulting DateTime is midnight (00:00:00). The Kind property is initialized to Unspecified The allowable values for year, month, and day depend on calendar. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including GregorianCalendar and JulianCalendar.
The following code example uses the SpecifyKind method to demonstrate how the Kind property influences the ToLocalTime and ToUniversalTime conversion methods.
Option Explicit Dim DateTime Set DateTime = DotNetFactory.CreateInstance( "System.DateTime", ,1979, 7, 28) MsgBox DateTime.ToString() Set DateTime = Nothing
Set object = DotNetFactory.CreateInstance( "System.DateTime", , year, month, day, hour, minute, second )
Parameter
year month day hour
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). DotNetFactory Page 16 of 151
Dani Vainstein
Chapter 14
Page 17
minute second
System.DateTime object
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. ArgumentException - The specified parameters evaluate to less than MinValue or more than MaxValue.
Chapter 14
Page 18
Parameter
year month day hour minute second calendar
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). The Calendar that applies to this DateTime.
System.DateTime object
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. ArgumentException - The specified parameters evaluate to less than MinValue or more than MaxValue. ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
The Kind property is initialized to Unspecified. The allowable values for year, month, and day depend on calendar. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including GregorianCalendar and JulianCalendar.
Dani Vainstein
DotNetFactory
Page 18 of 151
Chapter 14
Page 19
Set object = DotNetFactory.CreateInstance( "System.DateTime", , year, month, day, hour, minute, second, kind )
Parameter
year month day hour minute second kind
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). One of the DateTimeKind values that indicates whether year, month, day, hour, minute and second specify a local time, Coordinated Universal Time (UTC), or neither.
System.DateTime object
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. ArgumentException The specified parameters evaluate to less than MinValue or more than MaxValue. Kind is not one of the DateTimeKind values.
Dani Vainstein
DotNetFactory
Page 19 of 151
Chapter 14
Page 20
Set object = DotNetFactory.CreateInstance( "System.DateTime", , _ year, month, day, hour, minute, second, millisecond )
Parameter
year month day hour minute second millisecond
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). The milliseconds (0 through 999).
System.DateTime object
ArgumentOutOfRangeException. year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. millisecond is less than 0 or greater than 999. ArgumentException The specified parameters evaluate to less than MinValue or more than MaxValue.
Dani Vainstein
DotNetFactory
Page 20 of 151
Chapter 14
Page 21
Set object = DotNetFactory.CreateInstance( "System.DateTime", , _ year, month, day, hour, minute, second, millisecond, calendar )
Parameter
year month day hour minute second millisecond calendar
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). The milliseconds (0 through 999). The Calendar that applies to this DateTime.
System.DateTime object
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. millisecond is less than 0 or greater than 999. ArgumentException - The specified parameters evaluate to less than MinValue or more than MaxValue. ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
The Kind property is initialized to Unspecified. The allowable values for year, month, and day depend on calendar. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including GregorianCalendar and JulianCalendar.
Dani Vainstein
DotNetFactory
Page 21 of 151
Chapter 14
Page 22
Set object = DotNetFactory.CreateInstance( "System.DateTime", , _ year, month, day, hour, minute, second, millisecond, kind )
Parameter
year month day hour minute second millisecond kind
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). The milliseconds (0 through 999). One 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 object
ArgumentOutOfRangeException . year is less than 1 or greater than 9999 month is less than 1 or greater than 12. day is less than 1 or greater than the number of days in month. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. millisecond is less than 0 or greater than 999. ArgumentException The specified parameters evaluate to less than MinValue or more than MaxValue. Kind is not one of the DateTimeKind values.
DateTime.DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind ) Constructor
Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
Set object = DotNetFactory.CreateInstance( "System.DateTime", , _ year, month, day, hour, minute, second, millisecond, calendar, kind )
Dani Vainstein
DotNetFactory
Page 22 of 151
Chapter 14
Page 23
Parameter
year month day hour minute second millisecond calendar kind
Description
The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in month). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). The milliseconds (0 through 999). The Calendar object that applies to this DateTime. One 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 object
ArgumentOutOfRangeException . year is not in the range supported by calendar.month is less than 1 or greater than 12. month is less than 1 or greater than the number of months in calendar. day is less than 1 or greater than the number of days in month.hour is less than 0 or greater than 23. hour is less than 0 or greater than 23. minute is less than 0 or greater than 59. second is less than 0 or greater than 59. millisecond is less than 0 or greater than 999. ArgumentException The specified parameters evaluate to less than MinValue or more than MaxValue. kind is not one of the DateTimeKind values. ArgumentNullException - calendar is a null reference (Nothing in Visual Basic).
The allowable values for year, month, and day parameters depend on the calendar parameter. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including GregorianCalendar and JulianCalendar.
DateTime Properties
Name
Date Day DayOfWeek
Description
Gets the date component of this instance. Gets the day of the month represented by this instance. Gets the day of the week represented by this instance. DotNetFactory Page 23 of 151
Dani Vainstein
Chapter 14
Page 24
DayOfYear Hour Kind Millisecond Minute Month Now Second Ticks TimeOfDay Today UtcNow Year
Gets the day of the year represented by this instance. Gets the hour component of the date represented by this instance. Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. Gets the milliseconds component of the date represented by this instance. Gets the minute component of the date represented by this instance. Gets the month component of the date represented by this instance. Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time. Gets the seconds component of the date represented by this instance. Gets the number of ticks that represent the date and time of this instance. Gets the time of day for this instance. Gets the current date. Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC). Gets the year component of the date represented by this instance.
DateTime.Date Property
Gets the date component of this instance.
object.Date
A new DateTime with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).
Dani Vainstein
DotNetFactory
Page 24 of 151
Chapter 14
Page 25
DateTime.Day Property
Gets the day of the month represented by this instance.
Value = object.Date
DateTime.DayOfWeek Property
Gets the day of the week represented by this instance.
Value = object.DayOfWeek
Dani Vainstein
DotNetFactory
Page 25 of 151
Chapter 14
Page 26
A DayOfWeek enumerated constant that indicates the day of the week. This property value ranges from zero, indicating Sunday, to six, indicating Saturday.
DateTime.DayOfYear Property
Gets the day of the year represented by this instance
object.DayOfYear
The following example returns the Day of The year for Today
Msgbox DotNetFactory.CreateInstance( "System.DateTime" ).Today.DayOfYear
Dani Vainstein
DotNetFactory
Page 26 of 151
Chapter 14
Page 27
DateTime.Hour Property
Gets the hour component of the date represented by this instance.
object.Hour
Print "Millisecond --> " & moment.Millisecond ' ** Millisecond gets 11. Set moment = Nothing
DateTime.Kind Property
Dani Vainstein
DotNetFactory
Page 27 of 151
Chapter 14
Page 28
Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
object.Kind
The following example uses Item to retrieve the FolderItem object representing the Windows folder and filtering the content
Option Explicit Dim saveNow, saveUtcNow, myDt Dim DateTimeKind Set DateTimeKind = DotNetFactory.CreateInstance( "System.DateTimeKind" ) Set saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).Now Print "saveNow = " & saveNow.Kind.GetHashCode & " --> " & saveNow.Kind Set saveUtcNow = DotNetFactory.CreateInstance( "System.DateTime" ).UtcNow Print "saveUtcNow = " & saveUtcNow.Kind.GetHashCode & " --> " & saveUtcNow.Kind Set myDt = _ DotNetFactory.CreateInstance( "System.DateTime" ).SpecifyKind( _ saveNow, DateTimeKind.Utc _ ) Print "myDt = " & myDt.Kind.GetHashCode & " --> " & myDt.Kind Set myDt = DotNetFactory.CreateInstance( "System.DateTime" ).SpecifyKind( _ saveNow, DateTimeKind.Local _ ) Print "myDt = " & myDt.Kind.GetHashCode & " --> " & myDt.Kind Set myDt = DotNetFactory.CreateInstance( "System.DateTime" ).SpecifyKind( _ saveNow, DateTimeKind.Unspecified _ ) Print "myDt = " & myDt.Kind.GetHashCode & " --> " & myDt.Kind ' ** Cleaning objects Set DateTimeKind = Nothing : Set saveNow = Nothing Set saveUtcNow = Nothing : Set myDt = Nothing
Dani Vainstein
DotNetFactory
Page 28 of 151
Chapter 14
Page 29
DateTime.Millisecond Property
Gets the milliseconds component of the date represented by this instance.
Value = object.Millisecond
The following code example demonstrates the Millisecond property. see : DateTime.Hour Property
DateTime.Minute Property
Gets the minute component of the date represented by this instance.
Value = object.Minute
The following code example demonstrates the Minute property. see : DateTime.Hour Property
DateTime.Month Property
Gets the month component of the date represented by this instance
Value = object.Month
The following code example demonstrates the Minute property. see : DateTime.Hour Property
DateTime.Now Property
Gets a DateTime object that is set to the current date and time on this computer, Dani Vainstein DotNetFactory Page 29 of 151
Page 30
Value = object.Now
DateTime.Second Property
Gets the seconds component of the date represented by this instance.
Value = object.Second
The following code example demonstrates the Second property. see : DateTime.Hour Property
DateTime.Ticks Property
Gets the number of ticks that represent the date and time of this instance
Value = object.Ticks
The number of ticks that represent the date and time of this instance. The value is between MinValue and MaxValue.
DateTime.TimeOfDay Property
Gets the time of day for this instance.
Value = object.TimeOfDay
Dani Vainstein
DotNetFactory
Page 30 of 151
Chapter 14
Page 31
A TimeSpan that represents the fraction of the day that has elapsed since midnight.
The following example uses Item to retrieve the FolderItem object representing the Windows folder and filtering the content
Option Explicit Dim saveNow, timeSpan Set saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).Now Print "saveNow = " & saveNow Set timeSpan = saveNow.TimeOfDay Print "Time since midnight -> Hours : " & _ timeSpan.Hours & ", Minutes : " & _ timeSpan.Minutes & ", Seconds : " & timeSpan.Seconds Set saveNow = Nothing : Set timeSpan = Nothing
DateTime.Today Property
Gets the current date..
Value = object.Today
A DateTime set to today's date, with the time component set to 00:00:00.
DateTime.UtcNow Property
Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
Value = object.UtcNow
Dani Vainstein
DotNetFactory
Page 31 of 151
Chapter 14
Page 32
Starting with the .NET Framework version 2.0, the return value is a DateTime whose Kind property returns Utc.
The following example returns the UtcNow property. DateTime.DateTime( int64, DateTimeKind ) Constructor
DateTime.Year Property
Gets the year component of the date represented by this instance.
Value = object.Year
The following code example demonstrates the Year property. see : DateTime.Hour Property
DateTime Methods
Name
Add AddDays AddHours AddMilliseconds AddMinutes AddMonths AddSeconds AddTicks AddYears Compare CompareTo DaysInMonth Equals
Description
Adds the value of the specified TimeSpan to the value of this instance Adds the specified number of days to the value of this instance. Adds the specified number of hours to the value of this instance. Adds the specified number of milliseconds to the value of this instance. Adds the specified number of minutes to the value of this instance. Adds the specified number of months to the value of this instance. Adds the specified number of seconds to the value of this instance. Adds the specified number of ticks to the value of this instance. Adds the specified number of years to the value of this instance. Compares two instances of DateTime and returns an indication of their relative values. Overloaded. Compares this instance to a specified object or value type and returns an indication of their relative values. Returns the number of days in the specified month and year. Overloaded. Returns a value indicating whether two DateTime objects, or a DateTime instance and another object or DateTime DotNetFactory Page 32 of 151
Dani Vainstein
Chapter 14
Page 33
are equal. FromBinary FromFileTime FromFileTimeUtc Deserializes a 64-bit binary value and recreates an original serialized DateTime object. Converts the specified Windows file time to an equivalent local time. Converts the specified Windows file time to an equivalent UTC time. Overloaded. Converts the value of this instance to all the string representations supported by the standard DateTime format specifiers. Returns the hash code for this instance. Returns the TypeCode for value type DateTime. Indicates whether this instance of DateTime is within the Daylight Saving Time range for the current time zone Returns an indication whether the specified year is a leap year. Adds a specified time interval to a specified date and time, yielding a new date and time. Determines whether two specified instances of DateTime are equal. Determines whether one specified DateTime is greater than another specified DateTime. Determines whether one specified DateTime is greater than or equal to another specified DateTime. Determines whether two specified instances of DateTime are not equal. Determines whether one specified DateTime is less than another specified DateTime. Determines whether one specified DateTime is less than or equal to another specified DateTime. Overloaded. Subtracts a specified DateTime or TimeSpan from a specified DateTime. Overloaded. Converts the specified string representation of a date and time to its DateTime equivalent. Overloaded. Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly. Creates a new DateTime object that represents the same time as the specified DateTime, but is designated in either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value. Overloaded. Subtracts the specified time or duration from this instance. Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object. Converts the value of the current DateTime object to a Windows file time. DotNetFactory Page 33 of 151
GetTimeFormats GetHashCode GetTypeCode IsDaylightSavingTime IsLeapYear op_Addition op_Equality op_GreaterThan op_GreaterThanOrEqual op_Inequality op_LessThan op_LessThanOrEqual op_Subtraction Parse
ParseExact
SpecifyKind
Chapter 14
Page 34
Converts the value of the current DateTime object to a Windows file time. Converts the value of the current DateTime object to local time. Converts the value of the current DateTime object to its equivalent long date string representation. Converts the value of the current DateTime object to its equivalent long time string representation. Converts the value of the current DateTime object to its equivalent short date string representation. Converts the value of the current DateTime object to its equivalent short time string representation. Overloaded. Overridden. Converts the value of the current DateTime object to its equivalent string representation. Converts the value of the current DateTime object to Coordinated Universal Time (UTC). Overloaded. Converts the specified string representation of a date and time to its DateTime equivalent. Overloaded. Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly.
TryParseExact
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
Parameter
value
Description
A TimeSpan that contains the interval to add.
A DateTime whose value is the sum of the date and time represented by this instance and the time interval represented by value.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation.
The following code example demonstrates the Add method. It calculates the day of the week that is 36 days (864 hours) from this moment.
Dani Vainstein
DotNetFactory
Page 34 of 151
Chapter 14
Page 35
Option Explicit Dim saveNow, duration, answer Set saveNow = DotNetFactory.CreateInstance( "System.DateTime" ).Now Set 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 = Nothing
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. The fractional part of value is the fractional part of a day. For example, 4.5 is equivalent to 4 days, 12 hours, 0 minutes, 0 seconds, 0 milliseconds, and 0 ticks. The value parameter is rounded to the nearest millisecond.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
Parameter
days
Description
A number of whole and fractional days. The value parameter can be negative or positive
A DateTime whose value is the sum of the date and time represented by this instance and the number of days represented by days
Dani Vainstein
DotNetFactory
Page 35 of 151
Chapter 14
Page 36
Print "Today is --> " & saveNow.ToString( "D" ) Print "Tomorrow --> " & saveNow.AddDays( 1 ).ToString( "D" ) Print "Yesterday --> " & saveNow.AddDays( -1 ).ToString( "D" ) Set saveNow = Nothing
Parameter
hours
Description
number of whole and fractional hours. The value parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance and the number of hours represented by hours.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. The fractional part of value is the fractional part of an hour. For example, 4.5 is equivalent to 4 hours, 30 minutes, 0 seconds, 0 milliseconds, and 0 ticks.. The value parameter is rounded to the nearest millisecond.
Parameter
Description
DotNetFactory Page 36 of 151
Dani Vainstein
Chapter 14
Page 37
value
A number of whole and fractional milliseconds. The value parameter can be negative or positive. Note that this value is rounded to the nearest integer.
A DateTime whose value is the sum of the date and time represented by this instance and the number of milliseconds represented by value.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. The fractional part of value is the fractional part of a millisecond. For example, 4.5 is equivalent to 4 milliseconds, and 5000 ticks, where one millisecond = 10000 ticks. The value parameter is rounded to the nearest millisecond.
Parameter
minutes
Description
A number of whole and fractional minutes. The value parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance and the number of minutes represented by minutes.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. The fractional part of value is the fractional part of a minute. For example, 4.5 is equivalent to 4 minutes, 30 seconds, 0 milliseconds, and 0 ticks. The value parameter is rounded to the nearest millisecond.
Chapter 14
Page 38
Parameter
months
Description
A number of months. The months parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance and months.
ArgumentOutOfRangeException months is less than -120,000 or greater than 120,000. The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. The AddMonths method calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object. If the resulting day is not a valid day in the resulting month, the last valid day of the resulting month is used. For example, March 31st + 1 month = April 30th. The time-of-day part of the resulting DateTime object remains the same as this instance.
Parameter
seconds
Description
A number of whole and fractional seconds. The value parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance and the number of seconds represented by seconds.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. Dani Vainstein DotNetFactory Page 38 of 151
Chapter 14
Page 39
A The fractional part of value is the fractional part of a second. For example, 4.5 is equivalent to 4 seconds, 500 milliseconds, and 0 ticks. The value parameter is rounded to the nearest millisecond.
Parameter
ticks
Description
A number of 100-nanosecond ticks. The value parameter can be positive or negative.
A DateTime whose value is the sum of the date and time represented by this instance and the time represented by ticks.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation.
Parameter years
Description
A number of years. The value parameter can be negative or positive.
A DateTime whose value is the sum of the date and time represented by this instance and the number of years represented by years.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
Dani Vainstein
DotNetFactory
Page 39 of 151
Chapter 14
Page 40
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation. The AddYears method calculates the resulting year taking into account leap years. The month and time-of-day part of the resulting DateTime object remains the same as this instance.
Parameter
dt1 dt2
Description
The first DateTime. The second DateTime.
A signed number indicating the relative values of dt1 and dt2 Less than zero - dt1 is less than dt2. Zero - dt1 equals dt2 Greater than zero - dt1 is greater than dt2.
Before comparing DateTime objects, insure that the objects represent times in the same time zone.
Dani Vainstein
DotNetFactory
Page 40 of 151
Chapter 14
Page 41
Compares this instance to a specified DateTime object and returns an indication of their relative values.
instance.CompareTo( value )
Parameter
value
Description
A DateTime object to compare.
A signed number indicating the relative values of this instance and the value parameter. Less than zero - This instance is less than value Zero - This instance is equal to value. Greater than zero - This instance is greater than value.
This method implements the System.IComparable interface and performs slightly better than the DateTime.CompareTo method because it does not have to convert the value parameter to an object. Before comparing DateTime objects, insure that the objects represent times in the same time zone.
This method implements the System.IComparable interface and performs slightly better than the DateTime.CompareTo method because it does not have to convert the value parameter to an object. Dani Vainstein DotNetFactory Page 41 of 151
Chapter 14
Page 42
Before comparing DateTime objects, insure that the objects represent times in the same time zone.
Parameter
year month
Description
The year. The month (a number ranging from 1 to 12).
The number of days in month for the specified year. For example, if month equals 2 for February, the return value is 28 or 29 depending upon whether year is a leap year.
ArgumentOutOfRangeException month is less than 1 or greater than 12. year is less than 1 or greater than 9999.
Dani Vainstein
DotNetFactory
Page 42 of 151
Chapter 14
Page 43
Dani Vainstein
DotNetFactory
Page 43 of 151
Chapter 14
Page 44
Dani Vainstein
DotNetFactory
Page 44 of 151
Chapter 14
Page 45
Parameter
value
Description
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 slightly better than the Equals method because the value parameter does not have to be converted to an object.
Chapter 14
Page 46
Parameter
t1 t2
Description
The first DateTime instance. The second DateTime instance.
true if the two DateTime values are equal; otherwise, false. This method implements the System.IEquatable interface, and performs slightly better than the Equals method because the value parameter does not have to be converted to an object.
instance.FromBinary( dateData )
Parameter
dateData
Description
A 64-bit signed integer that encodes the Kind property in a 2-bit field and the Ticks property in a 62-bit field
A DateTime object that is equivalent to the DateTime object that was serialized by the ToBinary method
Dani Vainstein
DotNetFactory
Page 46 of 151
Chapter 14
Page 47
Use the ToBinary method to convert the value of the current DateTime object to a binary value. Subsequently, use the binary value and the FromBinary method to recreate the original DateTime object. A local time, which is a Coordinated Universal Time adjusted to the local time zone, is represented by a DateTime structure whose Kind property has the value Local. If a local DateTime object is serialized in one time zone by the ToBinary method and deserialized in a different time zone by the FromBinary method, the local time represented by the resulting DateTime object is automatically adjusted to the second time zone. For example, consider a DateTime object that represents a local time of 3 P.M. An application executing in a western time zone uses the ToBinary method to convert that DateTime object to a binary value, then another application executing in a time zone three hours east of the original one uses the FromBinary method to convert the binary value to a new DateTime object. The value of the new DateTime object is 6 P.M., which represents the same point in time as the original 3 P.M. value, but is adjusted to local time in the eastern time zone.
Parameter
fileTime
Description
A Windows file time expressed in ticks.
A DateTime object that represents a local time equivalent to the date and time represented by the fileTime parameter.
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file. The fileTime parameter specifies a file time expressed in 100-nanosecond ticks. Starting with the .NET Framework version 2.0, the return value is a DateTime whose Kind property is Local.
Dani Vainstein
DotNetFactory
Page 47 of 151
Chapter 14
Page 48
Dim dteNow, DateTime Dim fCreationTime, fAge, LongNum Set LongNum = DotNetFactory.CreateInstance( "System.Int64" ) Set LongNum = LongNum.Parse( "126879894987978697" ) Set dteNow = DotNetFactory.CreateInstance( "System.DateTime" ).Now Set 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.TotalDays Set fAge = Nothing : Set fCreationTime = Nothing : Set dteNow = Nothing Set LongNum = Nothing
Parameter
fileTime
Description
A Windows file time expressed in ticks.
A DateTime object that represents a UTC time equivalent to the date and time represented by the fileTime parameter
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file. The fileTime parameter specifies a file time expressed in 100-nanosecond ticks. Starting with the .NET Framework version 2.0, the return value is a DateTime whose Kind property is Utc.
Dani Vainstein
DotNetFactory
Page 48 of 151
Chapter 14
Page 49
DateTime.GetTimeFormats Method
Name
GetTimeFormats()
Description
Converts the value of this instance to all the string representations supported by the standard DateTime format specifiers. Converts the value of this instance to all the string representations supported by the specified standard DateTime format specifier. Converts the value of this instance to all the string representations supported by the standard DateTime format specifiers and the specified culture-specific formatting information. Converts the value of this instance to all the string representations supported by the specified standard DateTime format specifier and culture-specific formatting information.
DateTime.GetDateTimeFormats (Char)
DateTime.GetDateTimeFormats (IFormatProvider)
DateTime.GetTimeFormats () Method
Converts the value of this instance to all the string representations supported by the standard DateTime format specifiers.
A string array where each element is the representation of the value of this instance formatted with one of the standard DateTime formatting specifiers.
Each element of the return value is formatted using information from the current culture. For more information about culture-specific formatting information for the current culture, see CultureInfo.CurrentCulture. For For more information about the standard formatting specifiers http://msdn2.microsoft.com/enus/library/system.globalization.datetimeformatinfo.aspx
Dani Vainstein
DotNetFactory
Page 49 of 151
Chapter 14
Page 50
For nFormat = 0 To july28Formats.Length - 1 Print july28Formats.GetValue( CLng( nFormat ) ) Next Set july28Formats = Nothing: Set july28 = Nothing
Parameter
format
Description
A Standard DateTime format string or a Custom DateTime Format String DotNetFactory Page 50 of 151
Dani Vainstein
Chapter 14
Page 51
A string array where each element is the representation of the value of this instance formatted with the format standard DateTime formatting specifier.
Each element of the return value is formatted using information from the current culture. For more information about culture-specific formatting information for the current culture, see CultureInfo.CurrentCulture. For For more information about the standard formatting specifiers http://msdn2.microsoft.com/enus/library/system.globalization.datetimeformatinfo.aspx
Parameter
provider
Description
An IFormatProvider that supplies culture-specific formatting information about this instance. DotNetFactory Page 51 of 151
Dani Vainstein
Chapter 14
Page 52
A string array where each element is the representation of the value of this instance formatted with one of the standard DateTime formatting specifiers.
Each element of the return value is formatted using culture-specific information supplied by provider. For For more information about the standard formatting specifiers http://msdn2.microsoft.com/enus/library/system.globalization.datetimeformatinfo.aspx
Dani Vainstein
DotNetFactory
Page 52 of 151
Chapter 14
Page 53
Parameter
format provider
Description
A Standard DateTime format string or a Custom DateTime Format String An IFormatProvider that supplies culture-specific formatting information about this instance.
A string array where each element is the representation of the value of this instance formatted with one of the standard DateTime formatting specifiers.
Each element of the return value is formatted using culture-specific information supplied by provider. For For more information about the standard formatting specifiers Dani Vainstein DotNetFactory Page 53 of 151
Chapter 14
Page 54
http://msdn2.microsoft.com/enus/library/system.globalization.datetimeformatinfo.aspx
DateTime.GetHashCode () Method
Returns the hash code for this instance.
returnValue = instance.GetHashCode()
Dani Vainstein
DotNetFactory
Page 54 of 151
Chapter 14
Page 55
DateTime.GetTypeCode () Method
Returns the TypeCode for value type DateTime.
instance.GetTypeCode()
The following code example demonstrates the GetTypeCode method. DateTime.GetHashCode() Method
DateTime.IsDaylightSavingTime () Method
Indicates whether this instance of DateTime is within the Daylight Saving Time range for the current time zone.
instance.IsDaylightSavingTime ()
true if Kind is Local or Unspecified and the value of this instance of DateTime is within the Daylight Saving Time range for the current time zone. false if Kind is Utc.
Dani Vainstein
DotNetFactory
Page 55 of 151
Chapter 14
Page 56
instance.IsLeapYear( year )
Parameter
year
Description
A 4-digit year.
instance.op_Addition( d, t )
Parameter
d t
Description
A DateTime object A TimeSpan object
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
Dani Vainstein
DotNetFactory
Page 56 of 151
Chapter 14
Page 57
Set 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 = Nothing
instance.op_Equality( d1, d2 )
Parameter
d1 d2
Description
A DateTime object A DateTime object
true if d1 and d2 represent the same date and time; otherwise, false.
Dani Vainstein
DotNetFactory
Page 57 of 151
Chapter 14
Page 58
Determines whether one specified DateTime is greater than another specified DateTime.
instance.op_GreaterThan( t1, t2 )
Parameter
t1 t2
Description
A DateTime object A DateTime object
instance.op_GreaterThanOrEqual( t1, t2 )
Parameter
t1 t2
Description
A DateTime object A DateTime object
instance.op_Equality( d1, d2 )
Parameter
d1 d2
Description
A DateTime object A DateTime object
Dani Vainstein
DotNetFactory
Page 58 of 151
Chapter 14
Page 59
true if d1 and d2 do not represent the same date and time; otherwise, false.
instance.op_LessThan( t1, t2 )
Parameter
t1 t2
Description
A DateTime object A DateTime object
instance.op_LessThanOrEqual( t1, t2 )
Parameter
t1 t2
Description
A DateTime object A DateTime object
DateTime.op_Subtraction Method
Name
DateTime.op_Subtraction (DateTime, DateTime) DateTime.op_Subtraction (DateTime, TimeSpan)
Description
Subtracts a specified date and time from another specified date and time, yielding a time interval. Subtracts a specified time interval from a specified date and time, yielding a new date and time.
Dani Vainstein
DotNetFactory
Page 59 of 151
Chapter 14
Page 60
Subtracts a specified date and time from another specified date and time, yielding a time interval.
instance.op_Subtract( d1, d2 )
Parameter
d1 d2
Description
A DateTime (the minuend). 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 or greater than MaxValue.
Dani Vainstein
DotNetFactory
Page 60 of 151
Chapter 14
Page 61
instance.op_Subtract( d, t )
Parameter
d t
Description
A DateTime. A TimeSpan.
This method subtracts the ticks value of t from the ticks value of d.
ArgumentOutOfRangeException - The resulting DateTime is less than . MinValue or greater than MaxValue.
The following code example demonstrates the equality operator. See DateTime.op_Subtraction( DateTime, DateTime ) Method
DateTime.Parse Method
Name
DateTime.Parse (String) DateTime.Parse (String, IFormatProvider) DateTime.Parse (String, Dani Vainstein
Description
Converts the specified string representation of a date and time to its DateTime equivalent. Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information. Converts the specified string representation of a date DotNetFactory Page 61 of 151
Chapter 14
Page 62
IFormatProvider, DateTimeStyles)
and time to its DateTime equivalent using the specified culture-specific format information and formatting style
instance.Parse( s )
Parameter
s
Description
string containing a date and time to convert.
ArgumentNullException - s is a null reference (Nothing in Visual Basic). FormatException - s does not contain a valid string representation of a date and time.
The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture. This method attempts to parse s completely and avoid throwing FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). The s parameter must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo topic
Dani Vainstein
DotNetFactory
Page 62 of 151
Chapter 14
Page 63
instance.Parse( s, provider )
Parameter
s provider
Description
string containing a date and time to convert. An IFormatProvider that supplies culture-specific format information about s.
ArgumentNullException - s is a null reference (Nothing in Visual Basic). FormatException - s does not contain a valid string representation of a date and time.
The string s is parsed using formatting information in the DateTimeFormatInfo object that is supplied either explicitly or implicitly by the provider parameter. This method attempts to parse s completely and avoid throwing FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). The s parameter must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo topic The provider parameter supplies culture-specific date and time formatting information. For example, the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. If provider 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 the ParseExact method instead of the Parse method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated, and therefore difficult to parse. The Parse method attempts to parse a string with several implicit parse patterns, all of which might fail. The ParseExact Dani Vainstein DotNetFactory Page 63 of 151
Chapter 14
Page 64
method, in contrast, requires you to explicitly designate one or more exact parse patterns that are likely to succeed.
Parameter
s provider styles
Description
string containing a date and time to convert. An IFormatProvider that supplies culture-specific format information about s. A bitwise combination of DateTimeStyles values that indicates the permitted format of s. A typical value to specify is None.
A DateTimeequivalent to the date and time contained in s as specified by provider and styles.
ArgumentNullException - s is a null reference (Nothing in Visual Basic). FormatException - s does not contain a valid string representation of a date and time. ArgumentException - styles contains an invalid combination of DateTimeStyles Dani Vainstein DotNetFactory Page 64 of 151
Chapter 14
Page 65
The string s is parsed using formatting information in the DateTimeFormatInfo object that is supplied either explicitly or implicitly by the provider parameter. This method attempts to parse s completely and avoid throwing FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). The s parameter must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo topic The provider parameter supplies culture-specific date and time formatting information. For example, the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. If provider 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 the ParseExact method instead of the Parse method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated, and therefore difficult to parse. The Parse method attempts to parse a string with several implicit parse patterns, all of which might fail. The ParseExact method, in contrast, requires you to explicitly designate one or more exact parse patterns that are likely to succeed.
DateTime.ParseExact Method
Name
DateTime.ParseExact (String, Dani Vainstein
Description
Converts the specified string representation of a date DotNetFactory Page 65 of 151
Chapter 14
Page 66
String, IFormatProvider)
and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly. Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly.
Parameter
s format provider
Description
A string containing a date and time to convert. The expected format of s. An IFormatProvider that supplies culture-specific format information about s.
A DateTime equivalent to the date and time contained in s as specified by format and 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 in format.
The s parameter contains the date and time to parse. If the s parameter contains only a time and no date, the current date is used. If the s parameter contains only a date and no time, midnight (00:00:00) is used. The s parameter cannot contain leading, inner, or trailing white space characters. The format parameter contains a pattern that corresponds to the expected format of Dani Vainstein DotNetFactory Page 66 of 151
Chapter 14
Page 67
the s parameter. The pattern in the format parameter consists of one or more custom format specifiers from the Custom DateTime Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard DateTime Format Strings table. If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H". The provider parameter supplies culture-specific date and time formatting information, such as the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. The format parameter is typically a culture represented by a CultureInfo object. If provider is a null reference (Nothing in Visual Basic), the current culture is used.
Parameter
s format provider
Description
A string containing a date and time to convert. The expected format of s. An IFormatProvider that supplies culture-specific format information DotNetFactory Page 67 of 151
Dani Vainstein
Chapter 14
Page 68
about s. styles A bitwise combination of DateTimeStyles values that indicates the permitted 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 in format. 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 contains only a time and no date, the current date is used. If the s parameter contains only a date and no time, midnight (00:00:00) is used. The s parameter cannot contain leading, inner, or trailing white space characters. The format parameter contains a pattern that corresponds to the expected format of the s parameter. The pattern in the format parameter consists of one or more custom format specifiers from the Custom DateTime Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard DateTime Format Strings table. If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H". The provider parameter supplies culture-specific date and time formatting information, such as the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. The format parameter is typically a culture represented by a CultureInfo object. If provider is a null reference (Nothing in Visual Basic), the current culture is used.
Parameter
s
Description
A string containing a date and time to convert.
Dani Vainstein
DotNetFactory
Page 68 of 151
Chapter 14
Page 69
An array of expected formats of s. An IFormatProvider that supplies culture-specific format information about s. A bitwise combination of DateTimeStyles values that indicates the permitted 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 in formats. 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 contains only a time and no date, the current date is used. If the s parameter contains only a date and no time, midnight (00:00:00) is used. The s parameter cannot contain leading, inner, or trailing white space characters. The format parameter contains a pattern that corresponds to the expected format of the s parameter. The pattern in the format parameter consists of one or more custom format specifiers from the Custom DateTime Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard DateTime Format Strings table. If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H". The provider parameter supplies culture-specific date and time formatting information, such as the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. The format parameter is typically a culture represented by a CultureInfo object. If provider is a null reference (Nothing in Visual Basic), the current culture is used.
myDateTimeFrenchValue = "16/02/1992 12:15:12" Set culture = DotNetFactory.CreateInstance( CULTURE_INFO, "System", "fr-FR", True )
Dani Vainstein
DotNetFactory
Page 69 of 151
Chapter 14
Page 70
Set DateTimeStyles = DotNetFactory.CreateInstance( _ "System.Globalization.DateTimeStyles" ) ' ** Creating array of Strings Set 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", 1 expectedFormats.SetValue "f", 2 : expectedFormats.SetValue "F", 3 Set myDateTimeFrench = DotNetFactory.CreateInstance( _ "System.DateTime" ).ParseExact( _ myDateTimeFrenchValue, _ expectedFormats, _ culture, _ DateTimeStyles.NoCurrentDateDefault ) MsgBox myDateTimeFrench.ToString() Set myDateTimeFrench = Nothing : Set culture = Nothing Set DateTimeStyles = Nothing : Set expectedFormats = Nothing Set SystemType = Nothing
Parameter
value kind
Description
A DateTime object. One of the DateTimeKind values.
A new DateTime object consisting of the same time represented by the value parameter and the DateTimeKind value specified by the kind parameter.
Dani Vainstein
DotNetFactory
Page 70 of 151
Chapter 14
Page 71
A DateTime object consists of a Kind field that indicates whether the time value is based on local time, Coordinated Universal Time (UTC), or neither, and a Ticks field that contains a time value measured in 100-nanosecond ticks. The SpecifyKind method creates a new DateTime object using the specified kind parameter and the original time value. The SpecifyKind method is useful in interoperability scenarios where you receive a DateTime object with an unspecified Kind field, but you can determine by independent means that the Ticks field represents local time or UTC.
The following code example demonstrates the DateTimeKind method. See Example
DateTime.Subtract Method
Name
DateTime.Subtract (DateTime) DateTime.Subtract (TimeSpan)
Description
Subtracts the specified date and time from this instance. Subtracts the specified duration from this instance.
Parameter
value
Description
An instance of DateTime.
A TimeSpan interval equal to the date and time represented by this instance minus the date and time represented by value
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime object. Instead, a new TimeSpan is returned whose value is the result of this operation. Before subtracting DateTime objects, insure that the objects represent times in the same time zone. Otherwise, the result will include the difference between time zones.
Dani Vainstein
DotNetFactory
Page 71 of 151
Chapter 14
Page 72
Dim date1, date2, date3, date4 Dim diff1 Set 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 = Nothing Set date4 = Nothing : Set diff1 = Nothing
Parameter
value
Description
An instance of TimeSpan.
A DateTime equal to the date and time represented by this instance minus the time interval represented by value.
ArgumentOutOfRangeException - The resulting DateTime is less than MinValue or greater than MaxValue.
This method does not change the value of this DateTime. Instead, a new DateTime is returned whose value is the result of this operation
Dani Vainstein
DotNetFactory
Page 72 of 151
Chapter 14
Page 73
DateTime.ToFileTime () Method
Converts the value of the current DateTime object to a Windows file time.
instance.ToFileTime()
The value of the current DateTime object expressed as a Windows file time.
ArgumentOutOfRangeException - The resulting file time would represent a date and time 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-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file. Previous versions of the ToFileTime method assume the current DateTime object is a local time. Starting with the.NET Framework version 2.0, the ToFileTime method uses the Kind property to determine whether the current DateTime object is a local time, a UTC time, or an unspecified kind of time which is treated as a local time.
Dani Vainstein
DotNetFactory
Page 73 of 151
Chapter 14
Page 74
DateTime.ToFileTimeUtc () Method
Converts the value of the current DateTime object to a Windows file time.
The value of the current DateTime object expressed as a Windows file time.
ArgumentOutOfRangeException - The resulting file time would represent a date and time 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-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file. Prior versions of the ToFileTimeUtc method assume the current DateTime object is a UTC time. Starting with the.NET Framework version 2.0, the ToFileTimeUtc method uses the Kind property to determine whether the current DateTime object is a local time, a UTC time, or an unspecified kind of time which is treated as a UTC time.
DateTime.ToLocalTime () Method
Converts the value of the current DateTime object to local time.
A DateTime object whose Kind property is Local, and whose value is the local time equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented as a DateTime object.
ArgumentOutOfRangeException - The resulting file time would represent a date and time before 12:00 midnight January 1, 1601 C.E. UTC..
Dani Vainstein
DotNetFactory
Page 74 of 151
Chapter 14
Page 75
The local time is equal to the UTC time plus the UTC offset. For more information about the UTC offset, see TimeZone.GetUtcOffset. The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.
DateTime.ToLongDateString () Method
Converts the value of the current DateTime object to its equivalent long date
returnValue = instance.ToLongDateString()
A string that contains the long date string representation of the current DateTime object.
ArgumentOutOfRangeException - The resulting file time would represent a date and time before 12:00 midnight January 1, 1601 C.E. UTC..
The value of the current DateTime object is formatted using the long date format character, 'D'. The long date format character represents the pattern defined by the LongDatePattern property associated with the current thread culture. The return value is identical to the value returned by specifying the "D" standard DateTime format string with the ToString(String) method. For more information about the current thread culture, see the CurrentCulture property. For more information about format characters, format patterns, and the output they produce, see the Formatting Overview topic. For more information about Dani Vainstein DotNetFactory Page 75 of 151
Chapter 14
Page 76
changing the format pattern associated with a format character, see the DateTimeFormatInfo class.
Dani Vainstein
DotNetFactory
Page 76 of 151
Chapter 14
Page 77
DateTime.ToLongTimeString () Method
Converts the value of the current DateTime object to its equivalent long time string representation.
returnValue = instance.ToLongTimeString()
A string that contains the long time string representation of the current DateTime object.
The value of the current DateTime object is formatted using the long date format character, 'D'. The long date format character represents the pattern defined by the LongDatePattern property associated with the current thread culture. The return value is identical to the value returned by specifying the "D" standard DateTime format string with the ToString(String) method. For more information about the current thread culture, see the CurrentCulture property. For more information about format characters, format patterns, and the output they produce, see the Formatting Overview topic. For more information about changing the format pattern associated with a format character, see the DateTimeFormatInfo class.
The following code example demonstrates the ToLongTimeString method. see Example
DateTime.ToShortDateString () Method
Converts the value of the current DateTime object to its equivalent short date string representation. Dani Vainstein DotNetFactory Page 77 of 151
Chapter 14
Page 78
returnValue = instance.ToShortDateString()
A string that contains the short date string representation of the current DateTime object.
The value of the current DateTime object is formatted using the long date format character, 'D'. The long date format character represents the pattern defined by the LongDatePattern property associated with the current thread culture. The return value is identical to the value returned by specifying the "D" standard DateTime format string with the ToString(String) method. For more information about the current thread culture, see the CurrentCulture property. For more information about format characters, format patterns, and the output they produce, see the Formatting Overview topic. For more information about changing the format pattern associated with a format character, see the DateTimeFormatInfo class.
The following code example demonstrates the ToLongTimeString method. see Example
DateTime.ToShortTimeString () Method
Converts the value of the current DateTime object to its equivalent short time string representation.
returnValue = instance.ToShortTimeString()
A string that contains the long time string representation of the current DateTime object.
The value of the current DateTime object is formatted using the long date format character, 'D'. The long date format character represents the pattern defined by the LongDatePattern property associated with the current thread culture. The return value is identical to the value returned by specifying the "D" standard DateTime format string with the ToString(String) method. For more information about the current thread culture, see the CurrentCulture property. For more information about format characters, format patterns, and the output they produce, see the Formatting Overview topic. For more information about changing the format pattern associated with a format character, see the DateTimeFormatInfo class.
The following code example demonstrates the ToShortTimeString method. see Example
Dani Vainstein
DotNetFactory
Page 78 of 151
Chapter 14
Page 79
DateTime.ToString Method
Name
DateTime.ToString () DateTime.ToString (IFormatProvider)
Description
Converts the value of the current DateTime object to its equivalent string representation. Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information. Converts the value of the current DateTime object to its equivalent string representation using the specified format. Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.
DateTime.ToString (String)
DateTime.ToString () Method
Converts the value of the current DateTime object to its equivalent string representation.
returnValue = instance.ToString()
The value of the current DateTime object is formatted using the general date and time format specifier ('G'). The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics: For more information about date and time format specifiers, see Standard DateTime Format Strings and Custom DateTime Format Strings. For more information about formatting, see Formatting Types and Formatting Overview. This method uses formatting information derived from the current culture. For more information, see CurrentCulture.
Dani Vainstein
DotNetFactory
Page 79 of 151
Chapter 14
Page 80
msg.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_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_GENLONG_TIME", "(G) General date/long time (default) -->
msg.Add "MSG_ROUNDTRIP_UNS", "(o) Roundtrip (Unspecified) --> " msg.Add "MSG1", "Using ToString( String ) and the current thread culture." & vbCrLf msg.Add "MSG2", "Using ToString( String, IFormatProvider ) " & _ " and a specified culture." & vbCrLf msg.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:" & vbCrLf Print msg( "MSG_THIS_DATE" ) & thisDate.ToString() & vbCrLf Print 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.DisplayName Print msg( "MSG_SHORT_DATE" ) Print msg( "MSG_LONG_DATE" ) Print msg( "MSG_SHORT_TIME" ) Print msg( "MSG_LONG_TIME" ) Print msg( "MSG_FULLLONG_TIME" ) Print msg( "MSG_GENSHORT_TIME" ) Print msg( "MSG_GENLONG_TIME" ) Print msg( "MSG_MONTH" ) Print msg( "MSG_RFC1123" ) Print msg( "MSG_SORT" ) Print msg( "MSG_UNISOR_VAR" ) Print msg( "MSG_UNISORT" ) Print msg( "MSG_YEAR" ) Print msg( "MSG_ROUNDTRIP_LOC" ) Print msg( "MSG_ROUNDTRIP_UTC" ) Print msg( "MSG_ROUNDTRIP_UNS" ) Print String( 50, "=" ) & vbCrLf ' ** implements IFormatProvider. & & & & & & & & & thisDate.ToString( "d" ) thisDate.ToString( "D" )
thisDate.ToString( "t" ) thisDate.ToString( "T" ) thisDate.ToString( "f" ) thisDate.ToString( "F" ) & & thisDate.ToString( "g" ) thisDate.ToString( "G" )
thisDate.ToString( "M" ) utcDate.ToString( "R" ) & & thisDate.ToString( "s" ) utcDate.ToString( "u" )
thisDate.ToString( "U" ) thisDate.ToString( "Y" ) & & & thisDate.ToString( "o" ) utcDate.ToString( "o" ) unspecifiedDate.ToString( "o" )
' ** Display the same values using a CultureInfo object. The CultureInfo class
Dani Vainstein
DotNetFactory
Page 80 of 151
Chapter 14
Page 81
Print msg( "MSG2" ) ' ** Display the culture used to format the values. Set ci = DotNetFactory.CreateInstance( _ "System.Globalization.CultureInfo",, "de-DE" ) Print "Culture --> " & ci.DisplayName Print msg( "MSG_SHORT_DATE" ) Print msg( "MSG_LONG_DATE" ) Print msg( "MSG_SHORT_TIME" ) Print msg( "MSG_LONG_TIME" ) Print msg( "MSG_FULLLONG_TIME" ) Print msg( "MSG_GENSHORT_TIME" ) Print msg( "MSG_GENLONG_TIME" ) Print msg( "MSG_MONTH" ) Print msg( "MSG_RFC1123" ) Print msg( "MSG_SORT" ) Print msg( "MSG_UNISOR_VAR" ) Print msg( "MSG_UNISORT" ) Print msg( "MSG_YEAR" ) Print msg( "MSG_ROUNDTRIP_LOC" ) Print msg( "MSG_ROUNDTRIP_UTC" ) Print msg( "MSG_ROUNDTRIP_UNS" ) Print String( 50, "=" ) & vbCrLf Set dtk = Nothing : Set msg = Nothing Set thisDate = Nothing : Set utcDate = Nothing : Set unspecifiedDate = Nothing & & & & & & & & & thisDate.ToString( "d", ci ) thisDate.ToString( "D", ci )
thisDate.ToString( "t", ci ) thisDate.ToString( "T", ci ) thisDate.ToString( "f", ci ) thisDate.ToString( "F", ci ) & & thisDate.ToString( "g", ci ) thisDate.ToString( "G", ci )
thisDate.ToString( "M", ci ) utcDate.ToString( "R", ci ) & & thisDate.ToString( "s", ci ) utcDate.ToString( "u", ci )
thisDate.ToString( "U", ci ) thisDate.ToString( "Y", ci ) & & & thisDate.ToString( "o", ci ) utcDate.ToString( "o", ci ) unspecifiedDate.ToString( "o", ci )
Dani Vainstein
DotNetFactory
Page 81 of 151
Chapter 14
Page 82
Chapter 14
Page 83
Parameter
provider
Description
An IFormatProvider that supplies culture-specific formatting information.
The value of the current DateTime object is formatted using the general date and time format specifier ('G'). The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics: For more information about date and time format specifiers, see Standard DateTime Format Strings and Custom DateTime Format Strings. For more information about formatting, see Formatting Types and Formatting Overview. This method uses formatting information derived from the current culture. For more information, see CurrentCulture.
The following code example demonstrates the ToString method. see Example ToString
Parameter
format
Description
A DateTime format string.
FormatException The length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo. format does not contain a valid custom format pattern. Dani Vainstein DotNetFactory Page 83 of 151
Chapter 14
Page 84
The format parameter should contain either a format specifier character or a custom format pattern. For more information, see the summary page for System.Globalization.DateTimeFormatInfo. If format is a null reference (Nothing in Visual Basic) or an empty string, the general format specifier, 'G', is used. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics: For more information about date and time format specifiers, see Standard DateTime Format Strings and Custom DateTime Format Strings. For more information about formatting, see Formatting Types and Formatting Overview.
The following code example demonstrates the ToString method. see also Example ToString
Option Explicit Dim DateTime Set 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
Dani Vainstein
DotNetFactory
Page 84 of 151
Chapter 14
Page 85
Parameter
format provider
Description
A DateTime format string. An IFormatProvider that supplies culture-specific formatting information.
A string representation of value of the current DateTime object as specified by format and provider
Exception
Format Exception The length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo. format does not contain a valid custom format pattern.
Dani Vainstein
DotNetFactory
Page 85 of 151
Chapter 14
Page 86
The format parameter should contain either a format specifier character or a custom format pattern. For more information, see the summary page for System.Globalization.DateTimeFormatInfo. If format is a null reference (Nothing in Visual Basic) or an empty string, the general format specifier, 'G', is used. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics: For more information about date and time format specifiers, see Standard DateTime Format Strings and Custom DateTime Format Strings. For more information about formatting, see Formatting Types and Formatting Overview.
The following code example demonstrates the ToString method. see Example ToString
DateTime.ToUniversalTime () Method
Converts the value of the current DateTime object to Coordinated Universal Time (UTC).
returnValue = instance.ToUniversalTime()
A DateTime object whose Kind property is Utc, and whose value is the UTC equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented by a DateTime object.
The UTC time is equal to the local time minus the UTC offset. For more information about the UTC offset, see TimeZone.GetUtcOffset. The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object. The value returned by this conversion is a DateTime object whose Kind property is Utc. Consequently, a valid result is returned even if ToUniversalTime is applied repeatedly to the same DateTime object. This method always uses the local time zone when making calculations.
DateTime.TryParse Method
Name
DateTime.TryParse (String, DateTime) DateTime.TryParse (String, IFormatProvider, DateTimeStyles, DateTime)
Description
Converts the specified string representation of a date and time to its DateTime equivalent. Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style. DotNetFactory Page 86 of 151
Dani Vainstein
Chapter 14
Page 87
Parameter
s
Description
A string containing a date and time to convert. When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is a null reference (Nothing in Visual Basic), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
result
The TryParse method is similar to the Parse method, except that the TryParse method does not throw an exception if the conversion fails. The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture. This method attempts to ignore unrecognized data and parse s completely. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes the time is 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). The s parameter must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo class. Notes to Callers: Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. One reason the TryParse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.
Dani Vainstein
DotNetFactory
Page 87 of 151
Chapter 14
Page 88
Set DateTime = DotNetFactory.CreateInstance( "System.DateTime" ) Set myDateTime = DotNetFactory.CreateInstance( "System.DateTime" ) If DateTime.TryParse( myDateTimeValue, myDateTime ) Then MsgBox myDateTime.ToString() End If Set DateTime = Nothing : Set myDateTime = Nothing
Parameter
s result styles
Description
A string containing a date and time to convert. An IFormatProvider object that supplies culture-specific formatting information about s. A bitwise combination of DateTimeStyles values that indicates the permitted format of s. A typical value to specify is None. When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is a null reference (Nothing in Visual Basic), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
result
ArgumentException If format is a null reference (Nothing in Visual Basic) or an empty string, the general format specifier, 'G', is used. The .NET Framework provides extensive formatting support, which is described in greater detail in the following formatting topics: styles is not a valid DateTimeStyles value. styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal ). Dani Vainstein DotNetFactory Page 88 of 151
Chapter 14
Page 89
The TryParse method is similar to the Parse method, except that the TryParse method does not throw an exception if the conversion fails. The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture. This method attempts to ignore unrecognized data and parse s completely. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes the time is 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). The s parameter must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo class. The provider parameter supplies culture-specific date and time formatting information. For example, it might supply the names of the days of the week in a particular language, or the preferred order of presentation for the month, day, and year. If provider is a null reference (Nothing in Visual Basic), the current culture is used. Notes to Callers: Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. One reason the TryParse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.
DateTime.TryParseExact Method
Name
DateTime.TryParseExact Method (String, String, IFormatProvider, DateTimeStyles, DateTime)
Description
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly
Dani Vainstein
DotNetFactory
Page 89 of 151
Chapter 14
Page 90
Parameter
s format provider style
Description
A string containing a date and time to convert. The expected format of s. An IFormatProvider object that supplies culture-specific formatting information about s. bitwise combination of one or more DateTimeStyles values that indicate the permitted format of s. When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is a null reference (Nothing in Visual Basic), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
result
ArgumentException styles is not a valid DateTimeStyles value. styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal ).
The TryParseExact method is similar to the ParseExact method, except that the TryParseExact method does not throw an exception if the conversion fails. The s parameter contains the date and time to parse. If the s parameter contains only a time and no date, the style parameter determines whether the current date or a default date is used. If the s parameter contains only a date and no time, midnight (00:00:00) is used. The style parameter also determines whether the s parameter can contain leading, inner, or trailing white space characters The format parameter contains a pattern that corresponds to the expected format of the s parameter. The pattern in the format parameter consists of one or more custom format specifiers from the Custom DateTime Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard DateTime Format Strings table. If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H". The provider parameter supplies culture-specific date and time formatting information, such as the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. The format parameter is typically a culture represented by a CultureInfo object. If provider is a null reference (Nothing in Visual Basic), the current culture is used.
Dani Vainstein
DotNetFactory
Page 90 of 151
Chapter 14
Page 91
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly.
Parameter
s formats provider style
Description
A string containing a date and time to convert. An array of expected formats of s. An IFormatProvider object that supplies culture-specific formatting information about s. bitwise combination of one or more DateTimeStyles values that indicate the permitted format of s. When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is a null reference (Nothing in Visual Basic), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
result
ArgumentException styles is not a valid DateTimeStyles value. styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal ).
The TryParseExact method is similar to the ParseExact method, except that the TryParseExact method does not throw an exception if the conversion fails. The s parameter contains the date and time to parse. If the s parameter contains only a time and no date, the style parameter determines whether the current date or a default date is used. If the s parameter contains only a date and no time, midnight (00:00:00) is used. The style parameter also determines whether the s parameter can contain leading, inner, or trailing white space characters The format parameter contains a pattern that corresponds to the expected format of the s parameter. The pattern in the format parameter consists of one or more custom format specifiers from the Custom DateTime Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard DateTime Format Strings table. If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H". The provider parameter supplies culture-specific date and time formatting information, such as the names of the days of the week in a particular language, or the preferred presentation order of the month, day, and year. The format Dani Vainstein DotNetFactory Page 91 of 151
Chapter 14
Page 92
parameter is typically a culture represented by a CultureInfo object. If provider is a null reference (Nothing in Visual Basic), the current culture is used.
System.TimeSpan Structure
A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day. Time intervals are measured in days for consistency 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 time interval. A tick is equal to 100 nanoseconds, and the value of a TimeSpan object can range from MinValue to MaxValue. A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. That is, a time interval consists of a positive or negative number of days without a time of day, or a number of days with a time of day, or only a time of day. For example, the text representation of a TimeSpan object initialized to 1.0e+13 ticks is "11.13:46:40", which means 11 days, 13 hours, 46 minutes, and 40 seconds. For more information see : http://msdn2.microsoft.com/en-us/library/system.timespan.aspx
System.TimeSpan Contructors
Initializes a new TimeSpan.
Name
TimeSpan (Int64) TimeSpan (Int32, Int32, Int32) TimeSpan (Int32, Int32, Int32, Int32) TimeSpan (Int32, Int32, Int32, Int32, Int32)
Description
Initializes a new TimeSpan to the specified number of ticks. Initializes a new TimeSpan to a specified number of hours, minutes, and seconds. Initializes a new TimeSpan to a specified number of days, hours, minutes, and seconds. Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.
Parameter
Description
Dani Vainstein
DotNetFactory
Page 92 of 151
Chapter 14
Page 93
ticks
System.TimeSpan object
ArgumentOutOfRangeException - ticks is less than MinValue or greater than MaxValue. ArgumentException - Kind is not one of the DateTimeKind values.
The following code example creates several TimeSpan objects using the constructor overload that initializes a TimeSpan to a specified number of ticks.
Option Explicit Dim int64 ' ** Create a TimeSpan object and display its value. Sub CreateTimeSpan( ByRef ticks ) Dim ctor, elapsedStr Dim pointIndex, elapsedTime Set 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 & " ---> " & End Sub elapsedStr
Print "This example of the TimeSpan( Long ) constructor " & _ vbCrLf & "generates the following output." & vbCrLf CreateTimeSpan( 1 ) CreateTimeSpan( 999999 ) ' ** Beacause vbScript cannot handle numbers greater then Long.MaxValue Set 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
Dani Vainstein
DotNetFactory
Page 93 of 151
Chapter 14
Page 94
Parameter
hours minutes seconds
Description
Number of hours. Number of minutes. Number of seconds.
System.TimeSpan object
ArgumentOutOfRangeException - The parameters specify a TimeSpan value less than than MinValue or greater than MaxValue.
The specified hours, minutes, and seconds are converted to ticks, and that value initializes this instance.
The following code example creates several TimeSpan objects using the constructor overload that initializes a TimeSpan to a specified number of hours, minutes, and seconds.
Option Explicit ' ** Create a TimeSpan object and display its value. Sub CreateTimeSpan( ByVal hours, ByVal minutes, ByVal seconds ) Dim ctor, sb Dim elapsedTime Set elapsedTime = DotNetFactory.CreateInstance( _
Dani Vainstein
DotNetFactory
Page 94 of 151
Chapter 14
Page 95
"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 = Nothing End Sub Print "This example of the TimeSpan( Integer, Integer, Integer ) constructor " & _ vbCrLf & "generates the following output." & vbCrLf Call CreateTimeSpan( 10, 20, 30 ) Call CreateTimeSpan( -10, 20, 30 ) Call CreateTimeSpan( 0, 0, 37230 ) Call CreateTimeSpan( 1000, 2000, 3000 ) Call CreateTimeSpan( 1000, -2000, -3000 ) Call CreateTimeSpan( 999999, 999999, 999999 )
Parameter
days hours minutes seconds
Description
Number of days. Number of hours. Number of minutes. Number of seconds.
Dani Vainstein
DotNetFactory
Page 95 of 151
Chapter 14
Page 96
System.TimeSpan object
ArgumentOutOfRangeException - The parameters specify a TimeSpan value less than than MinValue or greater than MaxValue.
The specified days, hours, minutes, and seconds are converted to ticks, and that value initializes this instance.
The following code example creates several TimeSpan objects using the constructor overload that initializes a TimeSpan to a specified number of days, hours, minutes, and seconds.
Option Explicit ' ** Create a TimeSpan object and display its value. Sub CreateTimeSpan( ByVal Days, ByVal hours, ByVal minutes, ByVal seconds ) Dim ctor, sb Dim elapsedTime Set 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 = Nothing End Sub Print "This example of the TimeSpan " & _ " ( Integer, Integer, Integer, Integer ) constructor " & _ vbCrLf & "generates the following output." & vbCrLf Call 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 )
Dani Vainstein
DotNetFactory
Page 96 of 151
Chapter 14
Page 97
Parameter
days hours minutes seconds milliseconds
Description
Number of days. Number of hours. Number of minutes. Number of seconds. Number of milliseconds
System.TimeSpan object
ArgumentOutOfRangeException - The parameters specify a TimeSpan value less than than MinValue or greater than MaxValue.
The specified days, hours, minutes, seconds, and milliseconds are converted to ticks, and that value initializes this instance.
The following code example creates several TimeSpan objects using the constructor overload that initializes a TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.
Option Explicit ' ** Create a TimeSpan object and display its value. Sub CreateTimeSpan( _ ByVal Days, ByVal hours, ByVal minutes, ByVal seconds, ByVal milliseconds ) Dim ctor, sb Dim elapsedTime Set 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 = Nothing End Sub Print "This example of the TimeSpan " & _ " ( Integer, Integer, Integer, Integer, Integer ) constructor " & _ vbCrLf & "generates the following output." & vbCrLf Call CreateTimeSpan( 10, 20, 30, 40, 50 ) Call CreateTimeSpan( -10, 20, 30, 40, 50 )
Dani Vainstein
DotNetFactory
Page 97 of 151
Chapter 14
Page 98
Call 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 Fields
Name
MaxValue MinValue TicksPerDay TicksPerHour TicksPerMillisecond TicksPerMinute TicksPerSecond Zero
Description
Represents the maximum TimeSpan value. This field is read-only. Represents the minimum TimeSpan value. This field is read-only. Represents the number of ticks in 1 day. This field is constant. Represents the number of ticks in 1 hour. This field is constant. Represents the number of ticks in 1 millisecond. This field is constant. Represents the number of ticks in 1 minute. This field is constant. Represents the number of ticks in 1 second. Represents the zero TimeSpan value. This field is read-only
TimeSpan.MaxValue Field
Represents the maximum TimeSpan value. This field is read-only.
The value of this field is equivalent to Int64.MaxValue ticks. The string representation of this value is positive 10675199.02:48:05.4775807.
The following code example references and displays the value of the MaxValue field.
Option Explicit Dim timeSpan Set timeSpan = DotNetFactory.CreateInstance( "System.TimeSpan" ) Print _
Dani Vainstein
DotNetFactory
Page 98 of 151
Chapter 14
Page 99
"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 = Nothing
TimeSpan.MinValue Field
Represents the minimum TimeSpan value. This field is read-only.
The value of this field is equivalent to Int64.MinValue ticks. The string representation of this value is negative 10675199.02:48:05.4775808.
TimeSpan.TicksPerDay Field
Represents the number of ticks in 1 day. This field is constant.
TimeSpan.TicksPerHour Field
Represents 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. Dani Vainstein DotNetFactory Page 99 of 151
Chapter 14
Page 100
TimeSpan.TicksPerMillisecond Field
Represents the number of ticks in 1 millisecond. This field is constant.
TimeSpan.TicksPerMinute Field
Represents the number of ticks in 1 minute. This field is constant
TimeSpan.TicksPerSecond Field
Represents the number of ticks in 1 second.
TimeSpan.Zero Field
Represents the zero TimeSpan value. This field is read-only.
TimeSpan Properties
Name
Days Hours Milliseconds Minutes Seconds Ticks
Description
Gets the number of whole days represented by the current TimeSpan structure. Gets the number of whole hours represented by the current TimeSpan structure. Gets the number of whole milliseconds represented by the current TimeSpan structure. Gets the number of whole seconds represented by the current TimeSpan structure. Gets the number of whole seconds represented by the current TimeSpan structure. Gets the number of ticks that represent the value of the current TimeSpan structure.
Dani Vainstein
DotNetFactory
Chapter 14
Page 101
Gets the value of the current TimeSpan structure expressed in whole and fractional days. Gets the value of the current TimeSpan structure expressed in whole and fractional hours. Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds. Gets the value of the current TimeSpan structure expressed in whole and fractional minutes. Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.
TimeSpan.Days Property
Gets the number of whole days represented by the current TimeSpan structure.
returnValue = object.Days
The day component of this instance. The return value can be positive or negative.
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Days property is the day component, d.
The following code example creates several TimeSpan objects and displays the Days property of each.
Option Explicit Dim timeSpan, int64 ' ** Display the properties of the TimeSpan parameter. Sub ShowTimeSpanProperties( Byref interval ) Print "Interval : " & interval.ToString() Print "Days : " & interval.Days & vbTab & _ "TotalDays : " & interval.TotalDays Print "Hours : " & interval.Hours & vbTab & _ "TotalHours : " & interval.TotalHours Print "Minutes : " & interval.Minutes & vbTab & _ "TotalMinutes : " & interval.TotalMinutes Print "Seconds : " & interval.Seconds & vbTab & _ "TotalSeconds : " & interval.TotalSeconds Print "Milliseconds : " & interval.Milliseconds & vbTab & _ "TotalMilliseconds : " & interval.TotalMilliseconds Print "Ticks : " & interval.Ticks
Dani Vainstein
DotNetFactory
Chapter 14
Page 102
End Sub Print "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
Dani Vainstein
DotNetFactory
Chapter 14
Page 103
TimeSpan.Hours Property
Gets the number of whole days represented by the current TimeSpan structure.
Dani Vainstein
DotNetFactory
Chapter 14
Page 104
returnValue = object.Hours
The 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 optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Days property is the day component, d.
The following code example creates several TimeSpan objects and displays the Hours property of each. See Example TimeSpan Properties
TimeSpan.Milliseconds Property
Gets the number of whole milliseconds represented by the current TimeSpan structure.
returnValue = object.Milliseconds
The millisecond component of the current TimeSpan structure. The return value ranges from -999 through 999.
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Days property is the day component, d.
The following code example creates several TimeSpan objects and displays the Milliseconds property of each. See Example TimeSpan Properties
TimeSpan.Minutes Property
Gets the number of whole minutes represented by the current TimeSpan structure.
returnValue = object.Minutes
The minute component of the current TimeSpan structure. The return value ranges from -59 through 59.
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional Dani Vainstein DotNetFactory Page 104 of 151
Chapter 14
Page 105
minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Minutes property is the minute component, mm.
The following code example creates several TimeSpan objects and displays the Minutes property of each. See Example TimeSpan Properties
TimeSpan.Seconds Property
Gets the number of whole seconds represented by the current TimeSpan structure.
returnValue = object.Seconds
The second component of the current TimeSpan structure. The return value ranges from -59 through 59.
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Seconds property is the seconds component, ss.
The following code example creates several TimeSpan objects and displays the Seconds property of each. See Example TimeSpan Properties
TimeSpan.Ticks Property
Gets the number of ticks that represent the value of the current TimeSpan structure.
returnValue = object.Ticks
The smallest unit of time is the tick, which is equal to 100 nanoseconds. A tick can be negative or positive.
The following code example creates several TimeSpan objects and displays the Ticks property of each. See Example TimeSpan Properties
TimeSpan.TotalDays Property
Dani Vainstein
DotNetFactory
Chapter 14
Page 106
Gets the value of the current TimeSpan structure expressed in whole and fractional days.
returnValue = object.TotalDays
This property converts the value of this instance from ticks to days. This number might include whole and fractional days
The following code example creates several TimeSpan objects and displays the TotalDays property of each. See Example TimeSpan Properties
TimeSpan.TotalHours Property
Gets the value of the current TimeSpan structure expressed in whole and fractional hours.
returnValue = object.TotalHours
This property converts the value of this instance from ticks to hours. This number might include whole and fractional hours.
The following code example creates several TimeSpan objects and displays the TotalHours property of each. See Example TimeSpan Properties
TimeSpan.TotalMilliseconds Property
Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
returnValue = object.TotalMilliseconds
This property converts the value of this instance from ticks to milliseconds. This Dani Vainstein DotNetFactory Page 106 of 151
Chapter 14
Page 107
The following code example creates several TimeSpan objects and displays the TotalMilliseconds property of each. See Example TimeSpan Properties
TimeSpan.TotalMinutes Property
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
returnValue = object.TotalMinutes
This property converts the value of this instance from ticks to minutes. This number might include whole and fractional minutes.
The following code example creates several TimeSpan objects and displays the TotalMinutes property of each. See Example TimeSpan Properties
TimeSpan.TotalSeconds Property
Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.
returnValue = object.TotalSeconds
This property converts the value of this instance from ticks to seconds. This number might include whole and fractional seconds..
The following code example creates several TimeSpan objects and displays the TotalSeconds property of each. See Example TimeSpan Properties
TimeSpan Methods
Name
Add Dani Vainstein
Description
Adds the specified TimeSpan to this instance. DotNetFactory Page 107 of 151
Chapter 14
Page 108
Compares two TimeSpan values and returns an integer that indicates their relationship. Overloaded. Compares this instance to a specified object or TimeSpan and returns an indication of their relative values. Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object. Overloaded. Overridden. Returns a value indicating whether two instances of TimeSpan are equal. Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond. Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond. Returns a TimeSpan that represents a specified number of milliseconds. Returns a TimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond. Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. Returns a TimeSpan that represents a specified time, where the specification is in units of ticks. Overridden. Returns a hash code for this instance Gets the Type of the current instance Returns a TimeSpan whose value is the negated value of this instance. Adds two specified TimeSpan instances. Indicates whether two TimeSpan instances are equal. Indicates whether a specified TimeSpan is greater than another specified TimeSpan. Indicates whether a specified TimeSpan is greater than or equal to another specified TimeSpan. Indicates whether two TimeSpan instances are not equal. Indicates whether a specified TimeSpan is less than another specified TimeSpan. Indicates whether a specified TimeSpan is less than or equal to another specified TimeSpan. Subtracts a specified TimeSpan from another specified TimeSpan. Returns a TimeSpan whose value is the negated value of the specified instance. Returns the specified instance of TimeSpan. Constructs a new TimeSpan object from a time interval specified in a string.
FromHours
FromMillsecond
FromMinutes
FromSeconds
FromTicks GetHashCode GetType Negate op_Addition op_Equality op_GreaterThan op_GreaterThanOrEqual op_Inequality op_LessThan op_LessThanOrEqual op_Subtraction op_UnaryNegation op_UnaryPlus Parse
Dani Vainstein
DotNetFactory
Chapter 14
Page 109
Subtract ToString
Subtracts the specified TimeSpan from this instance. Overridden. Returns the string representation of the value of this instance. Constructs a new TimeSpan object from a time interval specified in a string. Parameters specify the time interval and the variable where the new TimeSpan object is returned.
TryParse
Parameter
ts
Description
A TimeSpan
A TimeSpan that represents the value of this instance plus the value of ts.
OverflowException - The resulting TimeSpan is less than MinValue or greater than MaxValue.
The return value must be between MinValue and MaxValue; otherwise, an exception 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 calculates their sum with the Add method.
Option Explicit Dim tsL, tsR, int64_1, int64_2 Sub ShowTimeSpanSumDiff( ByRef tsLeft, ByRef tsRight ) Print vbCrLf &"TimeSpan Left : " & tsLeft Print "TimeSpan Right : " & tsRight Print "Left.Add( Right ) : " & tsLeft.Add( tsRight ) Print "Left.Subtract( Right ) : " & tsLeft.Subtract( tsRight ) End Sub Print "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 " & _
Dani Vainstein
DotNetFactory
Chapter 14
Page 110
"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 = Nothing Set int64_1 = Nothing : Set int64_2 = Nothing )
Dani Vainstein
DotNetFactory
Chapter 14
Page 111
Parameter
t1 t2
Description
The first DateTime. The second DateTime.
A signed number indicating the relative values of t1 and t2 Less than zero - t1 is less than t2. Zero - t1 equals t2 Greater than zero - t1 is greater than t2.
The following code example compares several TimeSpan objects to a reference TimeSpan using the Compare method.
Option Explicit Dim ts, tsL, tsR, int64 ' ** Compare TimeSpan parameters, and display them with the results. Sub CompareTimeSpans( ByRef tsLeft, ByRef tsRight, ByVal RightText ) Dim sb Print "Right : " & RightText & " ---> " & tsRight Print "TimeSpan.Equals( Left, Right ) ---> " & ts.Equals( tsLeft, tsRight ) Print "TimeSpan.Compare( Left, Right ) ---> " & ts.Compare( tsLeft, tsRight ) End Sub Set 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." & vbCrLf Print vbNewLine Print "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 )
Dani Vainstein
DotNetFactory
Chapter 14
Page 112
Call CompareTimeSpans( tsL, tsR, "TimeSpan( 72000000000 )" ) Set int64 = Nothing Set tsr = ts.FromDays( 1 / 12 ) Call CompareTimeSpans( tsL, tsR, "TimeSpan.FromDays( 1 / 12 )" ) Set ts = Nothing : Set tsL = Nothing : Set tsR = Nothing
Parameter
value
Description
A TimeSpan object to compare to this instance.
A signed number indicating the relative values of t1 and t2 Less than zero - t1 is less than t2. Zero - t1 equals t2 Greater than zero - t1 is greater than t2.
Dani Vainstein
DotNetFactory
Chapter 14
Page 113
This method implements the System.IComparable interface and performs slightly better than the TimeSpan.CompareTo method because it does not have to convert the value parameter to an object.
TimeSpan.Duration ( ) Method
Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.
Set ts = instance.Duration()
A new TimeSpan whose value is the absolute value of the current TimeSpan object. Example
The following code example applies the Duration method to several TimeSpan objects.
Option Explicit Dim ts, unaryTs Sub ShowDurationNegate( Byref interval ) ' ** Display the TimeSpan value and the results of the ' methods. Print "Interval ---> " & interval ---> ---> " & interval.Duration " & interval.Negate Print "Interval.Duration Print "Interval.Negate End Sub Duration and Negate
Print "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 )
Dani Vainstein
DotNetFactory
Chapter 14
Page 114
Call ShowDurationNegate( ts ) Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 0, -10, 20, -30, 40 ) Set unaryTs = DotNetFactory.CreateInstance( "System.TimeSpan" ).op_UnaryPlus( ts ) Call ShowDurationNegate( ts ) Set ts = DotNetFactory.CreateInstance( "System.TimeSpan",, 1, 10, 20, 40, 160 ) Set unaryTs = DotNetFactory.CreateInstance("System.TimeSpan").op_UnaryNegation( ts ) Call ShowDurationNegate( ts ) Set ts = DotNetFactory.CreateInstance("System.TimeSpan",, -10, -20, -30, -40, -50 Call ShowDurationNegate( ts ) Set ts = Nothing : Set unaryTs = Nothing ) Set unaryTs = DotNetFactory.CreateInstance("System.TimeSpan").op_UnaryNegation( ts )
TimeSpan.Equals Method
Name
TimeSpan.Equals (TimeSpan) TimeSpan.Equals (TimeSpan, TimeSpan)
Description
Returns a value indicating whether this instance is equal to a specified TimeSpan object. Returns a value indicating whether two specified instances of TimeSpan are equal.
Dani Vainstein
DotNetFactory
Chapter 14
Page 115
Parameter
obj
Description
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 slightly better than Equals because it does not have to convert the the obj parameter to an object.
The following code example compares several TimeSpan objects to a reference TimeSpan using the Equals method. See Example Time Span Compare
Parameter
t1 t2
Description
A TimeSpan A TimeSpan
The following code example compares several TimeSpan objects to a reference TimeSpan using the Equals method. See Example Time Span Compare
Dani Vainstein
DotNetFactory
Chapter 14
Page 116
Parameter
value
Description
A number of days, accurate to the nearest millisecond.
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, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. If value is Double.PositiveInfinity, MaxValue is returned. If value is Double.NegativeInfinity, MinValue is returned.
The following code example creates several TimeSpan objects using the FromDays method.
Option Explicit Dim ts Sub GenTimeSpanFromDays( ByRef days ) Dim interval, timeInterval ' ** Create a TimeSpan object and TimeSpan string from a number of days. Set interval = ts.FromDays( days ) timeInterval = interval.ToString( ) Print "days ---> " & days Print "time Interval ---> " & timeInterval Set interval = Nothing End Sub Print "This example of TimeSpan.FromDays( Double )" & vbCrLf & _ "generates the following output." & vbCrLf Set 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
Dani Vainstein
DotNetFactory
Chapter 14
Page 117
Parameter
value
Description
A number of hours accurate to the nearest millisecond.
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, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. If value is Double.PositiveInfinity, MaxValue is returned. If value is Dani Vainstein DotNetFactory Page 117 of 151
Chapter 14
Page 118
The following code example creates several TimeSpan objects using the FromHours method.
Option Explicit Dim ts Sub GenTimeSpanFromHours( ByRef hours ) Dim interval, timeInterval ' ** Create a TimeSpan object and TimeSpan string from a number of hours. Set interval = ts.FromHours( hours ) timeInterval = interval.ToString( ) Print "hours ---> " & hours Print "time Interval ---> " & timeInterval Set interval = Nothing End Sub Print "This example of TimeSpan.FromHours( Double )" & _ vbCrLf & "generates the following output." & vbCrLf Set 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
Dani Vainstein
DotNetFactory
Chapter 14
Page 119
Parameter
value
Description
A number of milliseconds.
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, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. If value is Double.PositiveInfinity, MaxValue is returned. If value is Double.NegativeInfinity, MinValue is returned. Dani Vainstein DotNetFactory Page 119 of 151
Chapter 14
Page 120
The following code example creates several TimeSpan objects using the FromHours method.
Option Explicit Dim ts Sub GenTimeSpanFromMillisec( ByRef millisec ) Dim interval, timeInterval ' ** Create a TimeSpan object and TimeSpan string from a number of millisecs. Set interval = ts.FromMilliseconds( millisec ) timeInterval = interval.ToString( ) Print "milliseconds ---> " & millisec Print "time Interval ---> " & timeInterval Set interval = Nothing End Sub Print "This example of TimeSpan.FromMilliseconds ( Double )" & _ vbCrLf & "generates the following output." & vbCrLf Set 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
Dani Vainstein
DotNetFactory
Chapter 14
Page 121
Parameter
value
Description
A number of minutes, accurate to the nearest millisecond.
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, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. If value is Double.PositiveInfinity, MaxValue is returned. If value is Dani Vainstein DotNetFactory Page 121 of 151
Chapter 14
Page 122
Parameter
value
Description
A number of seconds, accurate to the nearest millisecond.
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, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. If value is Double.PositiveInfinity, MaxValue is returned. If value is Double.NegativeInfinity, MinValue is returned.
The following code example creates several TimeSpan objects using the FromHours method.
Option Explicit Dim ts Sub GenTimeSpanFromSeconds( ByRef seconds ) Dim interval, timeInterval ' ** Create a TimeSpan object and TimeSpan string from a number of seconds. Set interval = ts.FromSeconds( seconds ) timeInterval = interval.ToString( ) Print " seconds ---> " & seconds Print "time Interval ---> " & timeInterval Set interval = Nothing End Sub Print "This example of TimeSpan.FromMinutes ( Double )" & _ vbCrLf & "generates the following output." & vbCrLf Set ts = DotNetFactory.CreateInstance( "System.TimeSpan" ) Call GenTimeSpanFromSeconds ( 0.001 ) Call GenTimeSpanFromSeconds ( 0.0015 ) Call GenTimeSpanFromSeconds ( 12.3456 )
Dani Vainstein
DotNetFactory
Chapter 14
Page 123
Call 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 = Nothing
Parameter
value
Description
A number of ticks that represent a time.
Dani Vainstein
DotNetFactory
Chapter 14
Page 124
This is a convenience method with the same behavior as the TimeSpan constructor.
TimeSpan.GetHashCode ( ) Method
Returns a TimeSpan that represents a specified time, where the specification is in units of ticks.
returnValue = instance.GetHashCode()
Two TimeSpan objects might have the same hash code even though they represent different time values.
The following code example generates the hash codes of several TimeSpan objects using the GetHashCode method.
Option Explicit Dim ts, int64 Sub 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 Sub Print "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." & vbCrLf Set 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" )
Dani Vainstein
DotNetFactory
Chapter 14
Page 125
Set 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 = Nothing
TimeSpan.Negate ( ) Method
Returns a TimeSpan whose value is the negated value of this instance.
Dani Vainstein
DotNetFactory
Chapter 14
Page 126
returnValue = instance.GetHashCode()
The same numeric value as this instance, but with the opposite sign.
Two TimeSpan objects might have the same hash code even though they represent different time values.
OverflowException - The negated value of this instance cannot be represented by a TimeSpan; that is, the value of this instance is MinValue.
Parameter
t1 t2
Description
A TimeSpan. A TimeSpan.
OverflowException - The resulting TimeSpan is less than MinValue or greater than MaxValue.
The following code example creates several pairs of TimeSpan objects and calculates their sum with the Addition operator.
Option Explicit Dim ts, tsL, tsR, int64L, int64R ' ** 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
Dani Vainstein
DotNetFactory
Chapter 14
Page 127
Print "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 = Nothing Set tsL = Nothing : Set tsR = Nothing Set ts = Nothing
Dani Vainstein
DotNetFactory
Chapter 14
Page 128
Parameter
t1 t2
Description
A TimeSpan. A TimeSpan.
The following code example compares several TimeSpan objects to a reference TimeSpan using the Equality operator.
Option Explicit Dim 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 Sub Print "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 object Set ts = DotNetFactory.CreateInstance( "System.TimeSpan" ) Set tsL = DotNetFactory.CreateInstance( "System.TimeSpan",, 2, 0, 0 ) ' ** Create objects to compare with a 2-hour TimeSpan.
Dani Vainstein
DotNetFactory
Chapter 14
Page 129
Print "Left : TimeSpan( 2, 0, 0 ) ---> " & tsL 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 tsR = DotNetFactory.CreateInstance( "System.TimeSpan" ).FromDays( 1 / 12 ) Call CompareTimeSpans( tsL, tsr, "TimeSpan.FromDays( 1 / 12 )" ) Set tsL = Nothing : Set tsR = Nothing Set ts = Nothing
Dani Vainstein
DotNetFactory
Chapter 14
Page 130
Parameter
t1 t2
Description
A TimeSpan. 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 reference TimeSpan using the GreaterThan operator. See TimeSpan.op_Equality Example
Parameter
t1 t2
Description
A TimeSpan. 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 reference TimeSpan using the GreaterThanOrEqual operator. See TimeSpan.op_Equality Example
Dani Vainstein
DotNetFactory
Chapter 14
Page 131
Parameter
t1 t2
Description
A TimeSpan. A TimeSpan.
The following code example compares several TimeSpan objects to a reference TimeSpan using the Inequality operator. See TimeSpan.op_Equality Example
Parameter
t1 t2
Description
A TimeSpan. 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 reference TimeSpan using the LessThan operator. See TimeSpan.op_Equality Example
Dani Vainstein
DotNetFactory
Chapter 14
Page 132
Parameter
t1 t2
Description
A TimeSpan. 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 reference TimeSpan using the LessThanOrEqual operator. See TimeSpan.op_Equality Example
Parameter
t1 t2
Description
A TimeSpan. 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 than MaxValue.
The following code example creates several pairs of TimeSpan objects and calculates their difference with the Subtraction operator. See TimeSpan.op_Addition Example
TimeSpan.op_UnaryNegation ( ) Method
Returns a TimeSpan whose value is the negated value of the specified instance.
Set ts = instance.op_UnaryNegation( t )
Parameter
t
Description
A TimeSpan
Dani Vainstein
DotNetFactory
Chapter 14
Page 133
A TimeSpan with the same numeric value as this instance, but the opposite sign.
OverflowException - The negated value of this instance cannot be represented by a TimeSpan; that is, the value of this instance is MinValue.
The following code example applies the op_UnaryNegation method to several TimeSpan objects. See TimeSpan.Duration Method Example
TimeSpan.op_UnaryPlus ( ) Method
Returns the specified instance of TimeSpan.
Set ts = instance.op_UnaryPlus( t )
Parameter
t
Description
A TimeSpan
Returns t.
The following code example applies the op_UnaryNegation method to several TimeSpan objects. See TimeSpan.Duration Method Example
Set ts = instance.Parse( s )
Parameter
s
Description
A string that specifies a time interval.
ArgumentNullException - s is a null reference (Nothing in Visual Basic). FormatException - s has an invalid format. Dani Vainstein DotNetFactory Page 133 of 151
Chapter 14 OverflowException
Page 134
s represents a number less than MinValue or greater than MaxValue At least one of the days, hours, minutes, or seconds components is outside its valid range.
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 of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required; colons and periods (: and .) are literal characters and required; other items are as follows
Item
ws "-" d hh mm ss ff
Description
optional white space optional minus sign indicating a negative TimeSpan days, ranging from 0 to 10675199 hours, ranging from 0 to 23 minutes, ranging from 0 to 59 optional seconds, ranging from 0 to 59 optional fractional seconds, consisting of 1 to 7 decimal digits
The components of s must collectively specify a time interval greater than or equal to MinValue and less than or equal to MaxValue
The following code example uses the Parse method to create TimeSpan objects from valid TimeSpan strings and to raise exceptions from invalid TimeSpan strings.
Option Explicit Dim ts Private Sub ParseNDisplayTimeSpan( ByRef intervalStr ) Dim intervalVal, intervalToStr On 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 Then Print Err.Description Exit Sub End If intervalToStr = intervalVal.ToString( ) Print "String to Parse ---> " & intervalStr & _ " End Sub Print "This example of TimeSpan.Parse( String ) and " & _ vbCrLf & "TimeSpan.ToString( ) " & _ "generates the following output." & vbCrLf TimeSpan or Exception ---> " & intervalToStr
Dani Vainstein
DotNetFactory
Chapter 14
Page 135
Set 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 = Nothing
Parameter
ts
Description
A TimeSpan
A TimeSpan.
Dani Vainstein
DotNetFactory
Chapter 14
Page 136
OverflowException - The return value TimeSpan is less than MinValue or greater than MaxValue.
The return value must be between MinValue and MaxValue; otherwise, an exception 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 calculates their difference with the Subtract method. See Example TimeSpan Subtract and Add Methods
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
ws "-" d hh mm ss ff
Description
optional white space optional minus sign indicating a negative TimeSpan days, ranging from 0 to 10675199 hours, ranging from 0 to 23 minutes, ranging from 0 to 59 optional seconds, ranging from 0 to 59 optional fractional seconds, consisting of 1 to 7 decimal digits
For more information about comparing the string representation of TimeSpan and Oracle data types, see article Q324577, "System.TimeSpan Does Not Match Oracle 9i INTERVAL DAY TO SECOND Data Type," in the Microsoft Knowledge Base at http://support.microsoft.com.
Dani Vainstein
DotNetFactory
Chapter 14
Page 137
specify the time interval and the variable where the new TimeSpan object is returned.
Parameter
s result
Description
A string that specifies a time interval. When this method returns, contains an object that represents the time interval specified by s, or Zero if the conversion failed. This parameter is passed uninitialized.
true if s was converted successfully; otherwise, false. This operation returns false if the s parameter is a null reference (Nothing in Visual Basic), has an invalid format,represents a time interval less than MinValue or greater than MaxValue, or has at least one days, hours, minutes, or seconds component outside its valid range.
The TryParse method is like the TimeSpan.Parse method, except the TryParse method does not throw an exception if the conversion fails. The s parameter contains a time interval specification of the form: [ws][-]{ d | d.hh:mm[:ss[.ff]] | hh:mm[:ss[.ff]] }[ws] The TryParse method is like the TimeSpan.Parse method, except the TryParse method does not throw an exception if the conversion fails. Items in square brackets ([ and ]) are optional. One selection from the list of alternatives enclosed in braces ({ and }) and separated by vertical bars (|) is required. Colons and periods (: and .) are literal characters and required. Other items are as follows.
Item
ws "-" d hh mm ss ff
Description
optional white space optional minus sign indicating a negative TimeSpan days, ranging from 0 to 10675199 hours, ranging from 0 to 23 minutes, ranging from 0 to 59 optional seconds, ranging from 0 to 59 optional fractional seconds, consisting of 1 to 7 decimal digits
The components of s must collectively specify a time interval greater than or equal to MinValue and less than or equal to MaxValue.
Chapter 14
Page 138
Option Explicit Const CULTURE_INFO = "System.Globalization.CultureInfo" Dim calendarsArr, cultureArr, today Dim nCal, calName Dim nDay, nMonth, nYear Dim calDict Class CalendarInfo Private m_calendar, m_culture Private m_ciName, m_calName ' ** Class private events Private Sub Class_Initialize() Set m_calendar = Nothing : Set m_culture = Nothing End Sub Private Sub Class_Terminate() Set m_calendar = Nothing : Set m_culture = Nothing End Sub ' ** System.Globalization.CultureInfo Public Property Get CultureInfo() Set CultureInfo = m_culture End Property ' ** System.Globalization.Calendar Public Property Get Calendar() Set Calendar = m_calendar End Property Public Property Let CalendarName( ByVal value ) m_calName = value Set m_calendar = DotNetFactory.CreateInstance( _ "System.Globalization." & m_calName ) End Property Public Property Get CalendarName() CalendarName = m_calName End Property Public Property Let CultureName( ByVal value ) m_ciName = value Set m_culture = DotNetFactory.CreateInstance( _ CULTURE_INFO, "System", m_ciName, True ) Set m_culture.DateTimeFormat.Calendar = m_calendar End Property Public Property Get CultureName() CultureName = m_ciName End Property Public Function GetMonthNames( ByVal nYear ) Dim i, outStr For i = 1 To m_calendar.GetMonthsInYear( nYear ) - 1 outStr = outStr & _ m_culture.DateTimeFormat.MonthNames.GetValue( CInt( i ) ) & ", " Next GetMonthNames = outStr End Function Public Function GetAbbrMonthNames( ByVal nYear ) Dim i, outStr
Dani Vainstein
DotNetFactory
Chapter 14
Page 139
For i = 1 To m_calendar.GetMonthsInYear( nYear ) - 1 outStr = outStr & _ m_culture.DateTimeFormat.AbbreviatedMonthNames.GetValue( CInt( i ) ) & ", " Next GetAbbrMonthNames = outStr End Function Public Function GetDaysInMonth( ByVal nYear ) Dim i, outStr For i = 1 To m_calendar.GetMonthsInYear( nYear ) outStr = outStr & m_calendar.GetDaysInMonth( nYear, Clng( i ) ) & ", " Next GetDaysInMonth = outStr End Function End Class Set today = DotNetFactory.CreateInstance( "System.DateTime" ).Today Set 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 dictionary For nCal = LBound( calendarsArr ) To UBound( calendarsArr ) calName = calendarsArr( nCal ) calDict.Add calendarsArr( nCal ), New CalendarInfo calDict( calName ).CalendarName = calName ' ** Not all calendars are supported by cultureInfo If StrComp( cultureArr( nCal ), vbNullString ) <> 0 Then calDict( calName ).CultureName = cultureArr( nCal ) End If nYear = Clng( calDict( calName ).Calendar.GetYear( today ) ) Print calDict( calName ).Calendar.GetType() & " Current Year : " & nYear Print "Algorithm Type: " & calDict( calName ).Calendar.AlgorithmType Print "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 Then Print "NativeCalendarName: " & _ calDict( calName ).CultureInfo.DateTimeFormat.NativeCalendarName Print "MonthNames: " & calDict( calName ).GetMonthNames( nYear ) Print "AbbreviatedMonthNames: " & calDict(calName).GetAbbrMonthNames(nYear) End If nMonth = 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 ) )
Dani Vainstein
DotNetFactory
Chapter 14
Page 140
Print String( 70, "=" ) Set today = Nothing : Set calDict = Nothing
System.Collections.ArrayList
Option Explicit Dim ArrayList, i, nItem Private Sub PrintArray( ByRef arrayList, ByVal msg ) Dim outStr, Enumerator
Dani Vainstein
DotNetFactory
Chapter 14
Page 141
Set Enumerator = arrayList.GetEnumerator() Do While Enumerator.MoveNext() outStr = outStr & ", " & Enumerator.Current.ToString() Loop outStr = Mid( outStr, 2 ) Print msg & " ---> " & outStr Set Enumerator = Nothing End Sub Set ArrayList = DotNetFactory.CreateInstance( "System.Collections.ArrayList",, 15 ) For i = 1 To 10 nItem = RandomNumber( 1, 100 ) ArrayList.Add nItem Next Print "ArrayList.ToString : " & ArrayList.ToString Print "Array Properties" Print String( 18, "*" ) Print "ArrayList.Count : " & ArrayList.Count Print "ArrayList.Capacity : " & ArrayList.Capacity Print "ArrayList.IsFixedSize : " & ArrayList.IsFixedSize Print "ArrayList.IsReadOnly : " & ArrayList.IsReadOnly Print "ArrayList.IsSynchronized : " & ArrayList.IsSynchronized Call PrintArray( ArrayList, "Random Array" ) ArrayList.Sort Call PrintArray( ArrayList, "Sorted Array" ) Print "Contains 33? ---> " & ArrayList.Contains( 33 ) Print "Contains " & nItem & "? ---> " & ArrayList.Contains( nItem ) Print "IndexOf " & nItem & " ---> " & ArrayList.IndexOf( nItem ) ArrayList.Add 11 Call PrintArray( ArrayList, "After added '11'" ) ArrayList.RemoveAt 3 Call PrintArray( ArrayList, "After removed index '3'" ) ArrayList.TrimToSize Print "After TrimToSize, ArrayList.Capacity : " & ArrayList.Capacity ArrayList.Reverse Call PrintArray( ArrayList, "Reverse Array" ) Set ArrayList = Nothing
Dani Vainstein
DotNetFactory
Chapter 14
Page 142
Call Func2() Call Sub3() CallChain.Pop End Function Private Function Func2() CallChain.Push( Environment( "ActionName" ) & "::Func2" ) Call Func4() CallChain.Pop End Function Private Sub Sub3() CallChain.Push( Environment( "ActionName" ) & "::Sub3") ' ** Do Something CallChain.Pop End Sub Private Function Func4() CallChain.Push( Environment( "ActionName" ) & "::Func4" ) ' ** Do Something CallChain.Pop End Function Public Sub ReportCallChain( ByVal saveToFile ) Dim ie, clone, dtStr Set ie = Createobject( "InternetExplorer.Application" ) ie.Visible = 1 Do While ie.Busy Wait 0, 500 ie.StatusText = "Waiting for Report..." Loop ie.Navigate "about:blank" ie.ToolBar = 0 : ie.AddressBar= 0 : ie.StatusBar = 0 : ie.MenuBar = 0 ie.Width = 500 : ie.Height = 600 : ie.Left = 0 : ie.Top = 0 dtStr = 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.Clone Do While clone.Count > 0 .Writeln "</tr><td width='50%'>" & clone.Pop() & "</td></tr>" Loop Set clone = Nothing .Writeln "</table></body></html>" : .Write() If IsEmpty( saveToFile ) Then Exit Sub .execCommand "saveas", True, saveToFile End With End 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 Dani Vainstein DotNetFactory Page 142 of 151
Chapter 14
Page 143
Command Tab and Type ReportCallChain Empty Then press enter and see what happens... Try again Typing ReportCallChain "C:\MyReport.html" You can add the ReportCallChain function to an associated library.
Dani Vainstein
DotNetFactory
Chapter 14
Page 144
VisualBasic Functions
Option Explicit Dim Dim vbi, vbs Dim response Print "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;;\Z\e\r\o ---> " & vbs.Format( 0, "$#,##0;;\Z\e\r\o" ) Print "$#,##0;;\Z\e\r\o ---> " & vbs.Format( 1, "$#,##0;;\Z\e\r\o" ) Print "$#,##0;;\Z\e\r\o ---> " & vbs.Format( -1, "$#,##0;;\Z\e\r\o" ) 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" )
Dani Vainstein
DotNetFactory
Chapter 14
Page 145
Value
2 0 1
Description
The time represented is local time. The time represented is not specified as either local time or Coordinated Universal Time (UTC). The time represented is UTC.
System.DayOfWeek Enumeration
Constant
Friday Monday Saturday Sunday Thursday Tuesday Wednesday
Val
5 1 6 0 4 2 3
Description
Indicates Friday. Indicates Monday. Indicates Saturday. Indicates Sunday. Indicates Thursday. Indicates Tuesday. Indicates Wednesday.
Name
Short date pattern Long Date Pattern Full date/time pattern (short time) Full date/time pattern (long time) General date/time pattern (short time) General date/time pattern (long time)
Description
Represents a custom DateTime format string defined by the current DatetimeFormatInfo.ShortDatePattern property. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.LongDatePattern property. Represents a combination of the long date (D) and short time (t) patterns, separated by a space.
Represents a custom DateTime format string defined by the current DatetimeFormatInfo.FullDateTimePattern property.
Represents a combination of the short date (d) and short time (t) patterns, separated by a space.
Represents a combination of the short date (d) and long time (T) patterns, separated by a space.
Dani Vainstein
DotNetFactory
Chapter 14
Page 146
M or m o
Represents a custom DateTime format string defined by the current DatetimeFormatInfo.MonthDayPattern property. Represents a custom DateTime format string using a pattern that preserves time zone information. The pattern is designed to round-trip DateTime formats, including the Kind property, in text. Then the formatted string can be parsed back using Parse or ParseExact with the correct Kind property value. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.RFC1123Pattern property. The pattern is a defined standard and the property is read-only. Therefore, it is always the same regardless of the culture used or the format provider supplied. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.SortableDateTimePattern property. This pattern is a defined standard and the property is read-only. Therefore, it is always the same regardless of the culture used or the format provider supplied. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.ShortTimePattern property. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.LongTimePattern property. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.UniversalSortableDateTimePattern property. This pattern is a defined standard and the property is read-only. Therefore, it is always the same regardless of the culture used or the format provider supplied. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.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. Represents a custom DateTime format string defined by the current DatetimeFormatInfo.YearMonthPattern property
R or r
RFC1123 pattern
Sortable date/time pattern; conforms to ISO 8601 Short time pattern Long time pattern Universal sortable date/time pattern Universal sortable date/time pattern Year month pattern
t T u
Y or y
Description
Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero. For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero. Represents the abbreviated name of the day of the week as defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames property. Represents the full name of the day of the week as defined in the current System.Globalization.DateTimeFormatInfo.DayNames property. Represents the most significant digit of the seconds fraction.
dd ddd
Dani Vainstein
DotNetFactory
Chapter 14
Page 147
Note that if the "f" format specifier is used alone, without other format specifiers, it is interpreted as the "f" standard DateTime format specifier (full date/time pattern). For more information about using a single format specifier, see Using Single Custom Format Specifiers. When you use this format specifier with the ParseExact or TryParseExact method, the number of "f" format specifiers that you use indicates the number of most significant digits of the seconds fraction to parse. ff fff ffff fffff ffffff fffffff F Represents the two most significant digits of the seconds fraction. Represents the three most significant digits of the seconds fraction. Represents the four most significant digits of the seconds fraction. Represents the five most significant digits of the seconds fraction. Represents the six most significant digits of the seconds fraction. Represents the seven most significant digits of the seconds fraction. Represents the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero. For more information about using a single format specifier, see Using Single Custom Format Specifiers. When you use this format specifier with the ParseExact or TryParseExact method, the number of "F" format specifiers that you use indicates the maximum number of most significant digits of the seconds fraction to parse. FF FFF FFFF FFFFF FFFFFF FFFFFFF g or gg (plus any number of additional "g" specifiers) h Represents the two most significant digits of the seconds fraction. However, trailing zeros, or two zero digits, are not displayed. Represents the three most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed. Represents the four most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed. Represents the five most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed. Represents the six most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed. Represents the seven most significant digits of the seconds fraction. However, trailing zeros, or three zero digits, are not displayed. Represents the period or era (A.D. for example). This specifier is ignored if the date to be formatted does not have an associated period or era string. For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the hour as a number from 1 through 12, that is, the hour as represented by a 12-hour clock that counts the whole hours since midnight or noon. Consequently, a particular hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded, and a single-digit hour is formatted without a leading zero. For example, given a time of 5:43, this format specifier displays "5". For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the hour as a number from 01 through 12, that is, the hour as represented by a 12-hour clock that counts the whole hours since midnight or noon. Consequently, a particular hour after midnight is indistinguishable from the same hour after noon. The hour is not
Dani Vainstein
DotNetFactory
Chapter 14
Page 148
rounded, and a single-digit hour is formatted with a leading zero. For example, 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 hour as represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted without a leading zero. Represents the hour as a number from 00 through 23, that is, the hour as represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero. Represents different values of the DateTime.Kind property, that is, Local, Utc, or Unspecified. This specifier round-trips the kind value in text and preserves the time zone. For the Local kind value, this specifier is equivalent to the "zzz" specifier and displays the local offset, for example, "-07:00". For the Utc kind value, the specifier displays a "Z" character to represent a UTC date. For the Unspecified kind value, the specifier is equivalent to "" (nothing). Represents the minute as a number from 0 through 59. The minute represents whole minutes passed since the last hour. A single-digit minute is formatted without a leading zero. For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the minute as a number from 00 through 59. The minute represents whole minutes passed since the last hour. A single-digit minute is formatted with a leading zero. Represents the month as a number from 1 through 12. A single-digit month is formatted without a leading zero. For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the month as a number from 01 through 12. A single-digit month is formatted with a leading zero. Represents the abbreviated name of the month as defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames property Represents the full name of the month as defined in the current System.Globalization.DateTimeFormatInfo.MonthNames property. Represents the seconds as a number from 0 through 59. The second represents whole seconds passed since the last minute. A single-digit second is formatted without a leading zero. For more information about using a single format specifier, Using Single Custom Format Specifiers. Represents the seconds as a number from 00 through 59. The second represents whole seconds passed since the last minute. A single-digit second is formatted with a leading zero. Represents the first character of the A.M./P.M. designator defined in the current System.Globalization.DateTimeFormatInfo.AMDesignator or System.Globalization.DateTimeFormatInfo.PMDesignator property. The A.M. designator is used if the hour in the time being formatted is less than 12; otherwise, the P.M. designator is used. For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the A.M./P.M. designator as defined in the current System.Globalization.DateTimeFormatInfo.AMDesignator or System.Globalization.DateTimeFormatInfo.PMDesignator property. The A.M. designator is used if the hour in the time being formatted is less than 12; otherwise, the P.M. designator is used.
MM MMM
MMMM s
Dani Vainstein
DotNetFactory
Chapter 14
Page 149
Represents the year as at most a two-digit number. If the year has more 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 a leading zero. For more information about using a single format specifier, see Using Single Custom Format Specifiers. Represents the year as a two-digit number. If the year has more than two digits, only the two low-order digits appear in the result. If the year has fewer than two digits, the number is padded with leading zeroes to achieve two digits. Represents the year as a three-digit number. If the year has more than three digits, only the three low-order digits appear in the result. If the year has fewer than three digits, the number is padded with leading zeroes to achieve three digits. Note that for the Thai Buddhist calendar, which can have five-digit years, this format specifier displays all five digits.
yy
yyy
yyyy
Represents the year as a four-digit number. If the year has more than four digits, only the four low-order digits appear in the result. If the year has fewer than four digits, the number is padded with leading zeroes to achieve four digits. Note that for the Thai Buddhist calendar, which can have five-digit years, this format specifier renders all five digits
Represents the year as a five-digit number. If the year has more than five digits, only the five low-order digits appear in the result. If the year has fewer than five digits, the number is padded with leading zeroes to achieve five digits. If there are additional "y" specifiers, the number is padded with as many leading zeroes as necessary to achieve the number of "y" specifiers.
Represents the signed time zone offset of your system from Greenwich Mean Time (GMT) measured in hours. For example, the offset for a computer in the Pacific Standard Time zone is "-8". The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT. The offset ranges from 12 through +13. A single-digit offset is formatted without a leading zero. The offset is affected by daylight savings time. For more information about using a single format specifier, see Using Single Custom Format Specifiers.
zz
Represents the signed time zone offset of your system from Greenwich Mean Time (GMT) measured in hours. For example, the offset for a computer in the Pacific Standard Time zone is "-08". The offset is always displayed with a leading sign. A plus sign (+) indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT. The offset ranges from 12 through +13. A single-digit offset is formatted with a leading zero. The offset is affected by daylight savings time.
Represents the signed time zone offset of your system from Greenwich Mean Time (GMT) measured in hours and minutes. For example, the offset for a computer in the Pacific Standard Time zone is "-08:00". The offset is always displayed with a leading sign. A plus sign (+)
Dani Vainstein
DotNetFactory
Chapter 14
Page 150
indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT. The offset ranges from 12 through +13. A single-digit offset is formatted with a leading zero. The offset is affected by daylight savings time. : The time separator defined in the current System.Globalization.DateTimeFormatInfo.TimeSeparator property that is used to differentiate hours, minutes, and seconds. The date separator defined in the current System.Globalization.DateTimeFormatInfo.DateSeparator property that is used to differentiate years, months, and days. Quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Precede each quotation mark with an escape character (\). Quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters. Represents the result associated with a custom format specifier "c", when the custom DateTime format string consists solely of that custom format specifier. That is, to use the "d", "f", "F", "h", "m", "s", "t", "y", "z", "H", or "M" custom format specifier by itself, specify "%d", "%f", "%F", "%h", "%m", "%s", "%t", "%y", "%z", "%H", or "%M". For more information about using a single format specifier, see Using Single Custom Format Specifiers. The escape character. Displays the character "c" as a literal when that character is preceded by the escape character (\). To insert the backslash character itself in the result string, use two escape characters ("\\"). Any other character is copied to the result string, and does not affect formatting.
"
' %c
\c
System.Globalization.DateTimeStyles Enumeration
Member
AdjustToUniversal
Value
16
Description
Indicates that the date and time will be returned as a Coordinated Universal Time (UTC). Indicates that extra white-space characters in the middle of the string must be ignored during parsing, except if those white-space characters occur in the DateTimeFormatInfo format patterns. Indicates that leading white-space characters must be ignored during parsing, except if those white-space characters occur in the DateTimeFormatInfo format patterns. Indicates that trailing white-space characters must be ignored during parsing, except if those white-space characters occur in the DateTimeFormatInfo format patterns. Indicates that extra white-space characters anywhere in the string must be ignored during parsing, except if those white-space characters occur in the DateTimeFormatInfo format patterns. This value is a combination of the AllowLeadingWhite, AllowTrailingWhite, and AllowInnerWhite values.
AllowInnerWhite
AllowLeadingWhite
AllowTrailingWhite
AllowWhiteSpaces
Dani Vainstein
DotNetFactory
Chapter 14
Page 151
AssumeLocal
32
Indicates that if no time zone is specified in the parsed string, the string is assumed to denote a local time. Cannot be used with AssumeUniversal or RoundtripKind. Indicates that if no time zone is specified in the parsed string, the string is assumed to denote a Coordinated Universal Time (UTC). Cannot be used with AssumeLocal or RoundtripKind. Indicates that, if the parsed string contains only the time and not the date, the DateTime.Parse and DateTime.ParseExact methods assume the Gregorian date with year = 1, month = 1, and day = 1. If this value is not used, the current date is assumed. Indicates that the default formatting options must be used. This is the default style for DateTime.Parse, DateTime.ParseExact, and DateTime.TryParse. Preserves the DateTimeKind field of a date when a DateTime object is converted to a string and the string is then converted back to a DateTime object.
AssumeUniversal
64
NoCurrentDateDefault
None
RoundtripKind
128
Dani Vainstein
DotNetFactory