Time Formatting Parsing in C#

C# supports time formatting and parsing via format specifiers and custom format strings.

```csharp
using System;

class Program
{
    static void Main()
    {
        // Here's a basic example of formatting a time
        // according to ISO 8601, which is similar to RFC3339
        DateTime now = DateTime.Now;
        Console.WriteLine(now.ToString("o"));

        // Time parsing uses similar format specifiers as ToString
        DateTime t1 = DateTime.Parse("2012-11-01T22:08:41+00:00");
        Console.WriteLine(t1);

        // Custom format strings can be used for both formatting and parsing
        Console.WriteLine(now.ToString("h:mmtt"));
        Console.WriteLine(now.ToString("ddd MMM dd HH:mm:ss yyyy"));
        Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK"));

        string form = "h:mm tt";
        DateTime t2 = DateTime.ParseExact("8:41 PM", form, null);
        Console.WriteLine(t2);

        // For purely numeric representations you can also
        // use standard string formatting with the extracted
        // components of the time value
        Console.WriteLine($"{now.Year}-{now.Month:D2}-{now.Day:D2}T{now.Hour:D2}:{now.Minute:D2}:{now.Second:D2}-00:00");

        // Parse will throw a FormatException on malformed input
        try
        {
            DateTime.ParseExact("8:41PM", "ddd MMM dd HH:mm:ss yyyy", null);
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

This C# program demonstrates various ways to format and parse dates and times:

  1. We use DateTime.Now to get the current time and ToString("o") to format it according to ISO 8601.

  2. DateTime.Parse is used to parse a string representation of a date and time.

  3. Custom format strings are used with ToString() to format dates in various ways.

  4. DateTime.ParseExact is used to parse a string with a specific format.

  5. We show how to construct a formatted string using string interpolation and individual date/time components.

  6. Finally, we demonstrate error handling when parsing fails due to an incorrect format.

When you run this program, you’ll see output similar to the following:

2023-06-10T15:30:45.1234567+01:00
11/1/2012 10:08:41 PM
3:30PM
Sat Jun 10 15:30:45 2023
2023-06-10T15:30:45.1234567+01:00
6/10/2023 8:41:00 PM
2023-06-10T15:30:45-00:00
String was not recognized as a valid DateTime.

Note that the exact output will vary depending on the current date and time when you run the program.