Creating DateTime
There are several ways to create a DateTime object. A DateTime object can have a Date, Time, Localization, culture, milliseconds, and kind.
The code in Listing 1 uses various constructors of DateTime structure to create DateTime objects.
Private Sub CreateDateTime()
' Create a DateTime from date and time
Dim dob As DateTime = New DateTime(1974, 7, 10, 7, 10, 24)
' Create a DateTime from a String
Dim dateString As String = "7/10/1974 7:10:24 AM
Dim dateFromString As DateTime = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture)
Console.WriteLine(dateFromString.ToString())
' Empty DateTime
Dim emptyDateTime As DateTime = New DateTime()
' Just date
Dim justDate As DateTime = New DateTime(2002, 10, 18)
' DateTime from Ticks
Dim justTime As DateTime = New DateTime(1000000)
' DateTime with localization
Dim dateTimeWithKind As DateTime = New DateTime(1974, 7, 10, 7, 10, 24,DateTimeKind.Local)
' DateTime with date, time and milliseconds
Dim dateTimeWithMilliseconds As DateTime = New DateTime(2010, 12, 15, 5, 30, 45, 100)
End Sub
Listing 1
DateTime Properties
The Date and the Time properties of DateTime get the date and the time of a DateTime. Some self-explanatory DateTime properties are Day, Hour, Minute, Second, Millisecond, Year, Month, and Day.
Here is a list of some other properties with their brief description.
- DayOfWeek property returns the name of the day in a week.
- DayOfYear property returns the day of a year.
- TimeOfDay property returns the time element in a DateTime.
- Today property returns the DateTime object that has today's values. Time value is 12:00:00.
- Now property returns a DateTime object that has right now date and time values.
- UtcNow property returns a DateTime in Coordinated Universal Time (UTC)
- A tick represents one hundred nanoseconds or one ten-millionth of a second. Ticks property of DateTime returns the number of ticks in a DateTime.
- Kind property returns a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. The default value is unspecified.
The code listed in Listing 2 creates a DateTime object and reads its properties.
Private Sub GetDateTimeProperties()
Dim dob As DateTime = New DateTime(1974, 7, 10, 7, 10, 24)
Console.WriteLine("Day:{0}", dob.Day)
Console.WriteLine("Month:{0}", dob.Month)
Console.WriteLine("Year:{0}", dob.Year)
Console.WriteLine("Hour:{0}", dob.Hour)
Console.WriteLine("Minute:{0}", dob.Minute)
Console.WriteLine("Second:{0}", dob.Second)
Console.WriteLine("Millisecond:{0}", dob.Millisecond)
Console.WriteLine("Day of Week:{0}", dob.DayOfWeek)
Console.WriteLine("Day of Year: {0}", dob.DayOfYear)
Console.WriteLine("Time of Day:{0}", dob.TimeOfDay)
Console.WriteLine("Tick:{0}", dob.Ticks)
Console.WriteLine("Kind:{0}", dob.Kind)
End Sub