DateTime
is a built-in class in C# used to store dates and parse them to and from strings.
There are various ways to format time in C#:
using System;class HelloWorld{static void Main(){// Storing date as Stringstring dateString = "15/07/2020 06:30:45 PM";// Directly initializing date as DateTime variableDateTime date1 = new DateTime(2020, 7, 15, 18, 30, 45);// Parsing string to DateTimeDateTime date2 = DateTime.ParseExact(dateString, "dd/MM/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);// Both dates output 07 15 20 18:30:45Console.WriteLine(date1.ToString("MM dd yy HH:mm:ss"));Console.WriteLine(date2.ToString("MM dd yy HH:mm:ss"));// Outputs Wednesday July, 2020 06:30:45 PMConsole.WriteLine(date1.ToString("dddd MMMM, yyyy hh:mm:ss tt"));// Outputs 07/15/2020Console.WriteLine(date1.ToString("MM/dd/yyyy"));// Outputs 06:30:45 PMConsole.WriteLine(date1.ToString("hh:mm:ss tt"));}}
This example demonstrates how DateTime
variables are initialized and then parsed to strings. Parsing to and from a string can be done by comparing the string to a user-defined format.
C# allows users to define their own format using strings. Different components of time are represented in the format as different strings. Some of these are:
Free Resources