Search code examples
c#.netdatetimetimezone-offsettryparse

TryParseExact does not convert a string with timezone


I have a string "2023-04-13T07:03:20-03:00", and I want to convert to DateTime with a specific format "yyyy-MM-ddTHH:mm:ss", so i'm using the TryParseExact method, but I just receive false as return.

This is the code I'm working on. When the variable comes without timezone, the conversion happens normally, however with the timezone no format works.

In the documentation I didn't find anything that says that this way I'm doing it is wrong.

I also tried setting the datestyle to AssumeUniversal, it didn't work.

If anyone can give me some clarification I would appreciate it.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
                    
public class Program
{
    public static void Main()
    {
        var formats = new[]{
            "o",
                        "s",
                        "t", "T",
                        "M/yy",
                        "dd-MM-yy",
        "yyyy-MM-ddTHH:mm:ss",};
        
        foreach(var format in formats)
        {
            DateTime dat1;
            DateTime dat2;
            Console.WriteLine(format);
            Console.WriteLine("");
            Console.WriteLine(DateTime.TryParseExact("2023-04-13T07:03:20-03:00", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dat1) ? dat1.ToString(format) : "false");
            Console.WriteLine(DateTime.TryParseExact("2023-04-13T07:03:20", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dat2) ? dat2.ToString(format) : "false");
            Console.WriteLine("");
            Console.WriteLine("--------------------");
        }
    }
}

The result:

o

false 2023-04-13T07:03:20.0000000


s

false 2023-04-13T07:03:20


t

false 7:03 AM


T

false 7:03:20 AM


M/yy

false 4/23


dd-MM-yy

false 13-04-23


yyyy-MM-ddTHH:mm:ss

false 2023-04-13T07:03:20



Solution

  • You should include the timezone offset in the format. You can do it using "K".

    var formats = new[] { "yyyy-MM-ddTHH:mm:ssK" };