c sharp

How to Parse Dates with C# DateTime.Parse

In this tutorial, we will learn how to use to DateTime.Parse() method to parse the date and time values into a string representation that uses a given format. This is useful when you need to ensure the consistency in data formatting in the user output or database storage.

Let us explore the various examples and usage of the DateTime.Parse method.

Example 1: Basic Usage

The following example demonstrates how to use this function to parse a given date time into a DateTime object:

class Program
    {
        static void Main(string[] args)
        {
        string dateStr = "2023-10-12";
        DateTime date = DateTime.Parse(dateStr);
        Console.WriteLine(date);

    }
}

The previous code should convert the value into a DateTime object as shown in the output:

10/12/2023 12:00:00 AM

Example 2: Parsing the Date with Time

If you do not provide the time value, the function uses 0000hrs as the default value. However, you can provide a value as follows:

class Program
    {
        static void Main(string[] args)
        {
        string dateStr = "2023-10-12 22:53:34";
        DateTime date = DateTime.Parse(dateStr);
        Console.WriteLine(date);

    }
}

In this case, the date string includes the provided date value in the output as follows:

10/12/2023 10:53:34 PM

Example 3: Specifying the Timezone Info

If we pass the Timezone information, the method automatically parses the value as shown in the following example:

class Program
    {
        static void Main(string[] args)
        {
        string dateStr = "2023-10-12T22:55-07:00";
        DateTime date = DateTime.Parse(dateStr);
        Console.WriteLine(date);
    }
}

In the previous example, we specify the Timezone with the hour difference. This allows the “Parse” method to adjust the resulting DateTime object to reflect the changes.
An example is as follows:

10/13/2023 8:55:00 AM

Example 4: Using the Custom Format Specifiers

We can also specify a custom date and time specifier which allows the method to format the resulting DateTime object into the resulting format.

An example is as follows:

using System.Globalization;

class Program
    {
        static void Main(string[] args)
        {
        string dateStr = "13 December 2023";
        DateTime date = DateTime.ParseExact(dateStr, "dd MMMM yyyy", CultureInfo.InvariantCulture);
        Console.WriteLine(date);

    }
}

The resulting output is as follows:

12/13/2023 12:00:00 AM

Conclusion

This short tutorial describes how to use the “Parse” method to parse the date and time values into the DateTime objects. Feel free to explore the docs for more details.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list