You can create a new DateTime value in any of the following ways:
By calling any of the overloads of the
DateTime
constructor that allow you to specify specific elements of the date and time value (such as the year, month, and day, or the number of ticks).
The following statement illustrates a
call to one of the DateTime
constructors to create a date with a specific year, month, day, hour, minute, and second.
DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
By assigning the
DateTime
object a date and time value returned by a property or method.
The following example assigns the current date and time, the current
Coordinated Universal Time (UTC) date and time, and the current date to three new
DateTime
variables.
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
DateTime date3 = DateTime.Today;
By parsing the string representation of a date and time value.
The
Parse, ParseExact, TryParse, and TryParseExact
methods all convert a string to its equivalent date and time value.
The following example uses the Parse method to parse a string and convert it to a DateTime value.
string dateString = "19/6/2012 10:51:52 AM";
DateTime date1 = DateTime.Parse(dateString,
System.Globalization.CultureInfo.InvariantCulture);
By calling the
DateTime
structure's implicit default constructor. (For details on the implicit default constructor of a value type, see Value Types (C# Reference).) An approximate equivalent, for compilers that support it, is declaring a DateTime value without explicitly assigning a date and time to it.
The following example illustrates a call to the
DateTime
implicit default constructor in C# and Visual Basic, as well as a
DateTime
variable declaration with no assignment in Visual Basic.
DateTime dat1 = new DateTime();
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
Console.WriteLine(dat1.Equals(DateTime.MinValue));
Ref.:DateTime Structure[^]
Also have look on some more useful links:
C# DateTime[
^]
C# DateTime Format[
^]
Some more:
String Format for DateTime [C#][
^]