|
|
|
In this article we will explore some key language features which are frequently used by VB programmers.
DateTimes in VB.net
VB.net provides many new features for DateTime datatype. Unlike VB6 in VB.net you can initialize DateTime variable with verity of initial values. In VB.net you can initialize your datetime variable with 7 different ways. For example, |
DateTime Shared Members
The shared DateTime properties:
- Now : The current date and time as set on your system. Similar to the Visual Basic 6 function of the same name.
- Today : The current date as set on your system.
- UtcNow : The current date and time as set on your system, expressed as coordinated universal time (UTC), also known as Greenwich Mean Time.
- MinValue : The smallest possible value a DateTime can have.
- MaxValue : The largest possible value a DateTime can have.
DateTime Shared methods:
- DaysInMonth : Given a year and month, returns the number of days in that month.
- FromOADate : Returns a DateTime value that corresponds to the provided Ole Automation Date, which is a floating-point number representing the number of days from midnight, December 30, 1899. Use this method to convert dates stored in Microsoft Excel—for example, to .NET DateTime format.
- IsLeapYear : Given a four-digit year, returns True if it is a leap year and False otherwise.
DateTime Properties:
In addition to shared members, DateTime datatype offers instance specific methods and properties. Here is the list of properties which are instance specific
- Date : The date that dt contains.
- Day : An integer between 1 and 31, representing the dt day of the month.
- DayOfWeek : An enumerated constant that indicates the day of the week in the dt date, ranging from Sunday to Saturday.
- DayOfYear : An integer between 1 and 366, representing the dt day of the year.
- Hour : An integer between 0 and 23, representing the dt hour of day.
- Millisecond : An integer between 0 and 999, representing the millisecond of the dt time.
- Minute : An integer between 0 and 59, representing the minute of the dt time.
- Month : An integer between 1 and 12, representing the dt month of the year.
- Second : An integer between 0 and 59, representing the second of the dt time.
- Ticks : A Long containing the number of Ticks in the dt date and time, counting from 12:00 A.M., January 1, 0001. A Tick is a 100-nanosecond period of time.
- TimeOfDay : A TimeSpan that represents the fraction of the day between midnight and the dt time.
- Year : An integer that represents dt year, between 1 and 9999.
DateTime Methods:
In the previous version of VB6 we used to have various APIs to for different time conversions but now no more APIs. DateTime offers rich set of conversion functions which you can use for most of the time.
- ToFileTime : A system file time is a Long representing a date and time as 100-nanosecond intervals since January 1, 1601, 12:00 A.M.
- ToLocalTime : Assumes that the parameter passed to it represents UTC time, and returns a DateTime, converted to local time, allowing for daylight savings time. The opposite of ToUniversalTime.
- ToLongDateString : If the current culture is us-EN, returns a String with the date in the form: Monday, November 15, 2004. The format of the string varies depending on the current culture.
- ToLongTimeString : If the current culture is us-EN, returns a String with the time in the form: 5:03:29 PM. The format of the string varies depending on the current culture.
- ToOADate : Converts a DateTime to its OLE Automation date equivalent.
- ToShortDateString : If the current culture is us-EN, returns a String with the date in the form: 11/15/2004. The format of the string varies depending on the current culture.
- ToShortTimeString : If the current culture is us-EN, returns a String with the time in the form: 5:03:29 PM. The format of the string varies depending on the current culture.
- ToString : Presents the DateTime value as a string, with many formatting choices.
- ToUniversalTime : Assumes that the parameter passed to it represents local time, and returns a DateTime, converted to UTC time. The opposite of ToLocalTime.
- Parse : Converts the specified string representation of a date and time to its System.DateTime equivalent.
- ParseExact : Converts the specified string representation of a date and time to its System.DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
Date and Time Formatting
DateTime format strings are used to control the formatting produced when a date or time is represented as a string.
DateTime format strings fall into two categories: standard format strings and custom format strings. The custom format strings allow DateTime objects to be formatted for situations where the standard formatting strings are not useful. |
Format Specifier |
Name |
Example |
Output |
d |
Short date pattern |
Console.WriteLine(String.Format("{0:d}", Now)) |
8/22/2005 |
D |
Long date pattern |
Console.WriteLine(String.Format("{0:D}", Now)) |
Monday, August 22, 2005 |
t |
Short time pattern |
Console.WriteLine(String.Format("{0:t}", Now)) |
11:20 PM |
T |
Long time pattern |
Console.WriteLine(String.Format("{0:T}", Now)) |
11:20:55 PM |
f |
Full date/time pattern (short time) |
Console.WriteLine(String.Format("{0:f}", Now)) |
Monday, August 22, 2005 11:20 PM |
F |
Full date/time pattern (long time) |
Console.WriteLine(String.Format("{0:F}", Now)) |
Monday, August 22, 2005 11:20:55 PM |
g |
General date/time pattern (short time) |
Console.WriteLine(String.Format("{0:g}", Now)) |
8/22/2005 11:20 PM |
G |
General date/time pattern (long time) |
Console.WriteLine(String.Format("{0:G}", Now)) |
8/22/2005 11:20:55 PM |
M or m |
Month day pattern |
Console.WriteLine(String.Format("{0:m}", Now)) |
August 22 |
R or r |
RFC1123 pattern |
Console.WriteLine(String.Format("{0:r}", Now)) |
Mon, 22 Aug 2005 23:20:55 GMT |
s |
Sortable date/time pattern; conforms to ISO
8601 |
Console.WriteLine(String.Format("{0:s}", Now)) |
2005-08-22T23:20:55 |
u |
Universal sortable date/time pattern |
Console.WriteLine(String.Format("{0:u}", Now)) |
2005-08-22 23:20:55Z |
U |
Universal sortable date/time pattern |
Console.WriteLine(String.Format("{0:U}", Now)) |
Tuesday, August 23, 2005 3:20:55 AM |
Y or y |
Year month pattern |
Console.WriteLine(String.Format("{0:y}", Now)) |
August, 2005 |
Any other single character |
Unknown specifier |
Console.WriteLine(String.Format("{0:L}", Now)) |
System.FormatException |
|
Custom DateTime Format Strings
The following table illustrates the output created by applying some custom DateTime format strings to a particular date and time. |
Format Specifier |
Description |
Example (Date: Aug 9, 2005) |
Output |
d, dd |
Day |
Console.WriteLine(String.Format("{0:dd}", Now))
Console.WriteLine(String.Format("{0:M d}", Now))
Console.WriteLine(String.Format("{0:MMM dd}", Now))
|
10
8 10
Aug 10 |
ddd |
Day name (Short) |
Console.WriteLine(String.Format("{0:ddd}",
Now))
Console.WriteLine(String.Format("{0:MMM ddd, yyyy}", Now))
|
Wed
Aug Wed, 2005
|
dddd |
Day name (Full) |
Console.WriteLine(String.Format("{0:dddd}", Now))
Console.WriteLine(String.Format("{0:MMM dddd, yyyy}", Now))
|
Wednesday
Aug Wednesday, 2005 |
f, ff, fff, ffff, ... |
Second's fraction |
Console.WriteLine(String.Format("{0:fff}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.f}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.ffff}", Now)) |
859
12:18:37.8
12:18:37.8593 |
g, gg, ggg, gggg, ... |
Era |
Console.WriteLine(String.Format("{0:gg}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.fff g}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.fff ggg}", Now))
|
A.D.
12:18:37.859 A.D.
12:18:37.859 A.D. |
h , hh |
Displays the hour for the specified DateTime
in the range 1-12. |
Console.WriteLine(String.Format("{0:hh}", Now))
Console.WriteLine(String.Format("{0:h:m:s}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss}", Now))
|
12
12:18:37
12:18:37 |
H, HH |
Displays the hour for the specified
DateTime in the range 0-23. |
Console.WriteLine(String.Format("{0:HH}", Now))
Console.WriteLine(String.Format("{0:H:m:s}", Now))
Console.WriteLine(String.Format("{0:HH:mm:ss}", Now))
|
00
0:18:37
00:18:37 |
m, mm |
Minutes |
Console.WriteLine(String.Format("{0:mm}", Now))
Console.WriteLine(String.Format("{0:h:m:s}", Now))
Console.WriteLine(String.Format("{0:dd/MM/yyyy hh:mm:ss}", Now))
|
18
12:18:37
10/08/2005 12:18:37 |
M, MM |
Month |
Console.WriteLine(String.Format("{0:MM}", Now))
Console.WriteLine(String.Format("{0:d/M/yy}", Now))
Console.WriteLine(String.Format("{0:dd/MM/yyyy hh:mm:ss}", Now))
|
08
10/8/05
10/08/2005 12:18:37 |
MMM |
Month name (Short) |
Console.WriteLine(String.Format("{0:MMM}",
Now))
Console.WriteLine(String.Format("{0:MMM, yyyy}", Now))
|
Aug
Aug, 2005
|
MMMM |
Month name (Full) |
Console.WriteLine(String.Format("{0:MMMM}",
Now))
Console.WriteLine(String.Format("{0:MMMM, yyyy}", Now))
|
August
August, 2005 |
s, ss |
Second |
Console.WriteLine(String.Format("{0:ss}", Now))
Console.WriteLine(String.Format("{0:h:m:s}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss}", Now))
|
37
12:18:37
12:18:37 |
t, tt |
AM or PM |
Console.WriteLine(String.Format("{0:tt}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss t}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss tt}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss ttt}", Now))
|
AM
12:18:37 A
12:18:37 AM
12:18:37 AM |
y, yy, yyyy |
Year |
Console.WriteLine(String.Format("{0:yy}", Now))
Console.WriteLine(String.Format("{0:MM, yy}", Now))
Console.WriteLine(String.Format("{0:MM, yyy}", Now))
|
05
08, 05
08, 2005 |
z, zz |
Timezone offset (hours) |
Console.WriteLine(String.Format("{0:zz}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss z}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss zz}", Now))
|
-04
12:18:37 -4
12:18:37 -04 |
zzz |
Timezone offset (hours and minutes) |
Console.WriteLine(String.Format("{0:zzz}",
Now))
Console.WriteLine(String.Format("{0:hh:mm:ss G\MT zzz}", Now))
|
-04:00
12:18:37 GMT -04:00 |
'ABC' or "ABC" |
Literal value |
Console.WriteLine(String.Format("{0: 'Today
is :' MMM, dd yyyy hh:mm:ss tt G\MT zzz}", Now)) |
Today is : Aug, 10 2005 12:18:37 AM GMT
-04:00 |
|
Now lets look at the example which demonstrate varous DateTime methods and properties |
Click here to copy the following block | Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Console.WriteLine("".PadRight(50, "=")) Console.WriteLine("DateTime Demo") Console.WriteLine("".PadRight(50, "=")) DateTimeDemo() MsgBox("Check your output window (Clt + Alt + O)") End Sub
Sub DateTimeDemo() Const OUT_FORMAT = "{0,-40} : {1,-30}"
Dim MyDate As New DateTime(2005, 2, 28, 2, 11, 50, 999) Dim MyString As String
Console.WriteLine("'//DateTime Custom Formatting (" & MyDate.ToString("MM/dd/yyyy hh:mm:ss.fff tt zzz") & ")") DisplayDateTime(MyDate, "d - M - y") DisplayDateTime(MyDate, "dd - MM - yy") DisplayDateTime(MyDate, "ddd - MMM - yyy") DisplayDateTime(MyDate, "dddd - MMMM - yyyy") DisplayDateTime(MyDate, "MMM, dd yyyy h:m:s t") DisplayDateTime(MyDate, "MMM, dd yyyy hh:mm:ss tt") DisplayDateTime(MyDate, "MMM, dd yyyy hh:mm:ss.fff tt z") DisplayDateTime(MyDate, "MMM, dd yyyy hh:mm:ss.fff tt zz") DisplayDateTime(MyDate, "MMM, dd yyyy hh:mm:ss.fff tt zzz") DisplayDateTime(MyDate, "yyyy g") DisplayDateTime(MyDate, "yyyy gg")
Console.WriteLine() Console.WriteLine("'//DateTime Instance Properties (" & MyDate.ToString & ")") Console.WriteLine(OUT_FORMAT, "MyDate.Date", MyDate.Date) Console.WriteLine(OUT_FORMAT, "MyDate.DayOfWeek", MyDate.DayOfWeek) Console.WriteLine(OUT_FORMAT, "MyDate.DayOfYear", MyDate.DayOfYear) Console.WriteLine(OUT_FORMAT, "MyDate.Day", MyDate.Day) Console.WriteLine(OUT_FORMAT, "MyDate.Month", MyDate.Month) Console.WriteLine(OUT_FORMAT, "MyDate.Hour", MyDate.Hour) Console.WriteLine(OUT_FORMAT, "MyDate.Minute", MyDate.Minute) Console.WriteLine(OUT_FORMAT, "MyDate.Second", MyDate.Second) Console.WriteLine(OUT_FORMAT, "MyDate.Millisecond", MyDate.Millisecond) Console.WriteLine(OUT_FORMAT, "MyDate.Ticks", MyDate.Ticks) Console.WriteLine(OUT_FORMAT, "MyDate.Ticks", MyDate.TimeOfDay)
Console.WriteLine() Console.WriteLine("'//DateTime Shared Properties") Console.WriteLine(OUT_FORMAT, "MyDate.Today", MyDate.Today) Console.WriteLine(OUT_FORMAT, "MyDate.Now", MyDate.Now) Console.WriteLine(OUT_FORMAT, "MyDate.UtcNow", MyDate.UtcNow) Console.WriteLine(OUT_FORMAT, "MyDate.MinValue", MyDate.MinValue) Console.WriteLine(OUT_FORMAT, "MyDate.MaxValue", MyDate.MaxValue)
Console.WriteLine() Console.WriteLine("'//DateTime Shared Methods") Console.WriteLine(OUT_FORMAT, "MyDate.DaysInMonth(2004, 2)", MyDate.DaysInMonth(2004, 2)) Console.WriteLine(OUT_FORMAT, "MyDate.FromOADate(38568)", MyDate.FromOADate(38568)) Console.WriteLine(OUT_FORMAT, "MyDate.IsLeapYear(2004)", MyDate.IsLeapYear(2004))
Console.WriteLine() Console.WriteLine("'//DateTime Methods (" & MyDate.ToString & ")") Console.WriteLine(OUT_FORMAT, "MyDate.ToString", MyDate.ToString) Console.WriteLine(OUT_FORMAT, "MyDate.Add(New TimeSpan(5, 0, 30))", MyDate.Add(New TimeSpan(5, 59, 30))) Console.WriteLine(OUT_FORMAT, "MyDate.AddDays(2)", MyDate.AddDays(2)) Console.WriteLine(OUT_FORMAT, "MyDate.AddHours(5)", MyDate.AddHours(5)) Console.WriteLine(OUT_FORMAT, "MyDate.AddMilliseconds(20000)", MyDate.AddMilliseconds(20000)) Console.WriteLine(OUT_FORMAT, "MyDate.AddMinutes(7)", MyDate.AddMinutes(7)) Console.WriteLine(OUT_FORMAT, "MyDate.AddMonths(2)", MyDate.AddMonths(2)) Console.WriteLine(OUT_FORMAT, "MyDate.AddSeconds(3600)", MyDate.AddSeconds(3600)) Console.WriteLine(OUT_FORMAT, "MyDate.AddTicks(100000)", MyDate.AddTicks(100000))
Console.WriteLine() Console.WriteLine("'//DateTime Methods (" & MyDate.ToString & ")") Console.WriteLine(OUT_FORMAT, "MyDate.ToFileTime", MyDate.ToFileTime) Console.WriteLine(OUT_FORMAT, "MyDate.ToFileTimeUtc", MyDate.ToFileTimeUtc) Console.WriteLine(OUT_FORMAT, "MyDate.ToLocalTime", MyDate.ToLocalTime) Console.WriteLine(OUT_FORMAT, "MyDate.ToLongDateString", MyDate.ToLongDateString) Console.WriteLine(OUT_FORMAT, "MyDate.ToLongTimeString", MyDate.ToLongTimeString) Console.WriteLine(OUT_FORMAT, "MyDate.ToOADate", MyDate.ToOADate) Console.WriteLine(OUT_FORMAT, "MyDate.ToShortDateString", MyDate.ToShortDateString) Console.WriteLine(OUT_FORMAT, "MyDate.ToShortTimeString", MyDate.ToShortTimeString) Console.WriteLine(OUT_FORMAT, "MyDate.ToString", MyDate.ToString) Console.WriteLine(OUT_FORMAT, "MyDate.ToUniversalTime", MyDate.ToUniversalTime)
Dim sArr() As String, i As Integer sArr = MyDate.GetDateTimeFormats() For i = 0 To sArr.GetUpperBound(0) Console.WriteLine(OUT_FORMAT, "MyDate.GetDateTimeFormats()[Format#" & i & "]", sArr(i)) Next End Sub
Sub DisplayDateTime(ByVal dt As DateTime, ByVal strformat As String) Const OUT_FORMAT = "{0,-40} : {1,-30}"
Dim MyString As String MyString = dt.ToString(strformat) Console.WriteLine(OUT_FORMAT, strformat, MyString) End Sub |
==================================================
DateTime Demo
==================================================
'//DateTime Custom Formatting (02/28/2005 02:11:50.999 AM -05:00)
d - M - y : 28 - 2 - 5
dd - MM - yy : 28 - 02 - 05
ddd - MMM - yyy : Mon - Feb - 2005
dddd - MMMM - yyyy : Monday - February - 2005
MMM, dd yyyy h:m:s t : Feb, 28 2005 2:11:50 A
MMM, dd yyyy hh:mm:ss tt : Feb, 28 2005 02:11:50 AM
MMM, dd yyyy hh:mm:ss.fff tt z : Feb, 28 2005 02:11:50.999 AM -5
MMM, dd yyyy hh:mm:ss.fff tt zz : Feb, 28 2005 02:11:50.999 AM -05
MMM, dd yyyy hh:mm:ss.fff tt zzz : Feb, 28 2005 02:11:50.999 AM -05:00
yyyy g : 2005 A.D.
yyyy gg : 2005 A.D.
'//DateTime Instance Properties (2/28/2005 2:11:50 AM)
MyDate.Date : 2/28/2005 12:00:00 AM
MyDate.DayOfWeek : Monday
MyDate.DayOfYear : 59
MyDate.Day : 28
MyDate.Month : 2
MyDate.Hour : 2
MyDate.Minute : 11
MyDate.Second : 50
MyDate.Millisecond : 999
MyDate.Ticks : 632451535109990000
MyDate.TimeOfDay : 02:11:50.9990000
'//DateTime Shared Properties
MyDate.Today : 8/11/2005 12:00:00 AM
MyDate.Now : 8/11/2005 11:35:41 AM
MyDate.UtcNow : 8/11/2005 3:35:41 PM
MyDate.MinValue : 1/1/0001 12:00:00 AM
MyDate.MaxValue : 12/31/9999 11:59:59 PM
'//DateTime Shared Methods
MyDate.DaysInMonth(2004, 2) : 29
MyDate.FromOADate(38568) : 8/4/2005 12:00:00 AM
MyDate.IsLeapYear(2004) : True
'//DateTime Methods (2/28/2005 2:11:50 AM)
MyDate.ToString : 2/28/2005 2:11:50 AM
MyDate.Add(New TimeSpan(5, 59, 30)) : 2/28/2005 8:11:20 AM
MyDate.AddDays(2) : 3/2/2005 2:11:50 AM
MyDate.AddHours(5) : 2/28/2005 7:11:50 AM
MyDate.AddMilliseconds(20000) : 2/28/2005 2:12:10 AM
MyDate.AddMinutes(7) : 2/28/2005 2:18:50 AM
MyDate.AddMonths(2) : 4/28/2005 2:11:50 AM
MyDate.AddSeconds(3600) : 2/28/2005 3:11:50 AM
MyDate.AddTicks(100000) : 2/28/2005 2:11:51 AM
'//DateTime Methods (2/28/2005 2:11:50 AM)
MyDate.ToFileTime : 127540483109990000
MyDate.ToFileTimeUtc : 127540303109990000
MyDate.ToLocalTime : 2/27/2005 9:11:50 PM
MyDate.ToLongDateString : Monday, February 28, 2005
MyDate.ToLongTimeString : 2:11:50 AM
MyDate.ToOADate : 38411.0915624884
MyDate.ToShortDateString : 2/28/2005
MyDate.ToShortTimeString : 2:11 AM
MyDate.ToString : 2/28/2005 2:11:50 AM
MyDate.ToUniversalTime : 2/28/2005 7:11:50 AM
MyDate.GetDateTimeFormats()[Format#0] : 2/28/2005
MyDate.GetDateTimeFormats()[Format#1] : 2/28/05
MyDate.GetDateTimeFormats()[Format#2] : 02/28/05
MyDate.GetDateTimeFormats()[Format#3] : 02/28/2005
MyDate.GetDateTimeFormats()[Format#4] : 05/02/28
MyDate.GetDateTimeFormats()[Format#5] : 2005-02-28
MyDate.GetDateTimeFormats()[Format#6] : 28-Feb-05
...............
...............
...............
MyDate.GetDateTimeFormats()[Format#123] : Monday, 28 February, 2005 7:11:50
MyDate.GetDateTimeFormats()[Format#124] : Monday, 28 February, 2005 07:11:50
MyDate.GetDateTimeFormats()[Format#125] : 28 February, 2005 7:11:50 AM
MyDate.GetDateTimeFormats()[Format#126] : 28 February, 2005 07:11:50 AM
MyDate.GetDateTimeFormats()[Format#127] : 28 February, 2005 7:11:50
MyDate.GetDateTimeFormats()[Format#128] : 28 February, 2005 07:11:50
MyDate.GetDateTimeFormats()[Format#129] : February, 2005
MyDate.GetDateTimeFormats()[Format#130] : February, 2005
|
Click here to copy the following block | Sub ParseDateTimeDemo() Dim myDate As DateTime myDate = DateTime.Now() Console.WriteLine(myDate)
myDate = DateTime.Parse("9-30-2002") Console.WriteLine("Parse(9-30-2002) =>" & myDate)
Dim MyCultureInfo As Globalization.CultureInfo = New Globalization.CultureInfo("de-DE") Dim MyString As String = "12 Juni 2002" Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo) Console.WriteLine("Culture Specific parsing =>" & MyDateTime)
myDate = DateTime.ParseExact("09-05-2002 025612", "dd-MM-yyyy hhmmss", Nothing) Console.WriteLine("ParseExact(09-05-2002 025612) => " & myDate) myDate = DateTime.ParseExact("09052002", "ddMMyyyy", Nothing) Console.WriteLine("ParseExact(09052002) => " & myDate) myDate = DateTime.ParseExact("9-5-2002", "d-M-yyyy", Nothing) Console.WriteLine("ParseExact(9-5-2002) => " & myDate) myDate = DateTime.ParseExact("9-5-02", "d-M-yy", Nothing) Console.WriteLine("ParseExact(9-5-02) => " & myDate)
Dim allowedFomats() As String = {"ddMMyyyy", "d-MM-yyyy", "d-M-yy"} myDate = DateTime.ParseExact("9-01-02", allowedFomats, Nothing, Globalization.DateTimeStyles.None) Console.WriteLine("ParseExact using format array => " & myDate) Try myDate = DateTime.ParseExact("9 01 02", allowedFomats, Nothing, Globalization.DateTimeStyles.None) Catch ex As Exception Console.WriteLine(ex.Message) End Try End Sub |
8/2/2005 11:51:12 PM
Parse(9-30-2002) =>9/30/2002
Culture Specific parsing =>6/12/2002
ParseExact(09-05-2002 025612) => 5/9/2002 2:56:12 AM
ParseExact(09052002) => 5/9/2002
ParseExact(9-5-2002) => 5/9/2002
ParseExact(9-5-02) => 5/9/2002
ParseExact using format array => 1/9/2002
String was not recognized as a valid DateTime. |
TimeSpan object
TimeSpan is another very useful object in VB.net. TimeSpan can represent time measured in Ticks which is 100 nanoseconds interval. You can store time interval as TimeSpan for easy manipulation with DateTime datatype. Let’s look at the example how you can use TimeSpan with DateTime datatype.
Example: |
Click here to copy the following block | Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Console.WriteLine("".PadRight(50, "=")) Console.WriteLine("TimeSpan Demo") Console.WriteLine("".PadRight(50, "=")) TimeSpanDemo()
MsgBox("Check your output window (Clt + Alt + O)") End Sub
Sub TimeSpanDemo() Const headerFmt As String = vbCrLf & "{0,-45}"
Console.WriteLine( _ "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.")
Console.Write(headerFmt, "TimeSpan( 1 )") ShowTimeSpanProperties(New TimeSpan(1))
Console.Write(headerFmt, "TimeSpan( 111222333444555 )") ShowTimeSpanProperties(New TimeSpan(111222333444555))
Console.Write(headerFmt, "TimeSpan( 1111, 2222, 3333, 4444, 5555)") ShowTimeSpanProperties(New TimeSpan(1111, 2222, 3333, 4444, 5555))
Console.Write(headerFmt, "FromDays( 20.84745602 )") ShowTimeSpanProperties(TimeSpan.FromDays(20.84745602))
Console.Write(headerFmt, "FromSeconds( 378452 )") ShowTimeSpanProperties(TimeSpan.FromSeconds(378452))
Console.Write(headerFmt, "TimeSpan.Parse(""99.23:59:59.9999999"")") ShowTimeSpanProperties(TimeSpan.Parse("99.23:59:59.9999999"))
Dim dt As New DateTime(2005, 2, 28) dt = dt.Add(TimeSpan.Parse("2.02:56:30.999").Duration) Console.WriteLine("Add TimeSpan : " & dt.ToString("MMM dd, yyyy hh:mm:ss.fff tt"))
Dim dt1, dt2 As DateTime Dim ts As TimeSpan dt1 = "1/1/2005 02:00:00 PM" dt2 = "1/1/2006 03:30:50 PM"
ts = dt2.Subtract(dt1) Console.WriteLine("ts=dt1.subtract(dt1) : " & ts.ToString) End Sub
Sub ShowTimeSpanProperties(ByVal interval As TimeSpan) Const dataFmt As String = "{0,-12}{1,8} {2,-18}{3,21}"
Console.WriteLine("{0,21}", interval) Console.WriteLine(dataFmt, "Days", interval.Days, "TotalDays", interval.TotalDays) Console.WriteLine(dataFmt, "Hours", interval.Hours, "TotalHours", interval.TotalHours) Console.WriteLine(dataFmt, "Minutes", interval.Minutes, "TotalMinutes", interval.TotalMinutes) Console.WriteLine(dataFmt, "Seconds", interval.Seconds, "TotalSeconds", interval.TotalSeconds) Console.WriteLine(dataFmt, "Milliseconds", interval.Milliseconds, "TotalMilliseconds", interval.TotalMilliseconds) Console.WriteLine(dataFmt, Nothing, Nothing, "Ticks", interval.Ticks) End Sub |
==================================================
TimeSpan Demo
==================================================
This example of the TimeSpan class properties generates the
following output. It creates several TimeSpan objects and
displays the values of the TimeSpan properties for each.
TimeSpan( 1 ) 00:00:00.0000001
Days 0 TotalDays 1.15740740740741E-12
Hours 0 TotalHours 2.77777777777778E-11
Minutes 0 TotalMinutes 1.66666666666667E-09
Seconds 0 TotalSeconds 1E-07
Milliseconds 0 TotalMilliseconds 0.0001
Ticks 1
TimeSpan( 111222333444555 ) 128.17:30:33.3444555
Days 128 TotalDays 128.729552597865
Hours 17 TotalHours 3089.50926234875
Minutes 30 TotalMinutes 185370.555740925
Seconds 33 TotalSeconds 11122233.3444555
Milliseconds 344 TotalMilliseconds 11122233344.4555
Ticks 111222333444555
TimeSpan( 1111, 2222, 3333, 4444, 5555) 1205.22:47:09.5550000
Days 1205 TotalDays 1205.94941614583
Hours 22 TotalHours 28942.7859875
Minutes 47 TotalMinutes 1736567.15925
Seconds 9 TotalSeconds 104194029.555
Milliseconds 555 TotalMilliseconds 104194029555
Ticks 1041940295550000
FromDays( 20.84745602 ) 20.20:20:20.2000000
Days 20 TotalDays 20.8474560185185
Hours 20 TotalHours 500.338944444444
Minutes 20 TotalMinutes 30020.3366666667
Seconds 20 TotalSeconds 1801220.2
Milliseconds 200 TotalMilliseconds 1801220200
Ticks 18012202000000
FromSeconds( 378452 ) 4.09:07:32
Days 4 TotalDays 4.38023148148148
Hours 9 TotalHours 105.125555555556
Minutes 7 TotalMinutes 6307.53333333333
Seconds 32 TotalSeconds 378452
Milliseconds 0 TotalMilliseconds 378452000
Ticks 3784520000000
TimeSpan.Parse("99.23:59:59.9999999") 99.23:59:59.9999999
Days 99 TotalDays 99.9999999999988
Hours 23 TotalHours 2399.99999999997
Minutes 59 TotalMinutes 143999.999999998
Seconds 59 TotalSeconds 8639999.9999999
Milliseconds 999 TotalMilliseconds 8639999999.9999
Ticks 86399999999999
Add TimeSpan : Mar 02, 2005 02:56:30.999 AM
ts=dt1.subtract(dt1) : 365.01:30:50 |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|