Languages
[Edit]
PT

C# / .NET - converter ISO 8601 para DateTime

3 points
Created by:
Alyona
1114

ISO 8601 especifica diferentes formatos de data e hora. Em C# / .NET , é possível converter a string iso 8601 em objeto DateTime de algumas maneiras.

Solução rápida:

using System;
using System.Globalization;

public class Program
{
	public static void Main()
	{
		CultureInfo culture = CultureInfo.InvariantCulture;
		
		string text = "2019-08-18T07:36:13+01:00";
		DateTime time = DateTime.Parse(text, culture, DateTimeStyles.None);

		Console.WriteLine(time.ToString(culture));
	}
}

Veja abaixo exemplos diferentes:

1. Exemplo de detecção automática de formato

Nesta seção, apresentamos como o método interno (built-in method) lida com diferentes formatos de data e hora.

Apresentado abaixo, o código tenta detectar o formato da hora e imprimir o resultado no console. Como podemos ver, alguns formatos de data e hora não são suportados pela configuração padrão, que foi apresentada como PARSING ERROR! texto. 

Para resolver o problema, podemos definir uma lista personalizada de formatos suportados e usá-los para detectar o formato, se ocorrer um erro - consulte o exemplo da próxima seção para ver como ele funciona.

using System;
using System.Globalization;

public class Program
{
	public static void Main()
	{
		string[] dates = {
			"2019-08-18T07:36:13.5344729+01:00",

			"2019-08-18T07:36:13+01:00",
			"2019-08-18T07:36:13+01",
			"2019-08-18T07:36:13",
			"2019-08-18T07:36+01:00",
			"2019-08-18T07:36+01",
			"2019-08-18T07:36",
			"2019-08-18T07+01:00",
			"2019-08-18T07+01",
			"2019-08-18T07",
			"2019-08-18",

			"20190818T073613+01:00",
			"20190818T073613+01",
			"20190818T0736+01:00",
			"20190818T0736+01",
			"20190818T07+01:00",
			"20190818T07+01",
			"20190818T07",
			"20190818",

			"--08-18",

			"2019-08-18T06:36:13Z",
			"2019-08-18T06:36Z",
			"2019-08-18T06Z",

			"20190818T063613Z",
			"20190818T0636Z",
			"20190818T06Z"
		};

		CultureInfo culture = CultureInfo.InvariantCulture;

		foreach (string entry in dates)
		{
			DateTime time;

			if (DateTime.TryParse(entry, culture, DateTimeStyles.None, out time))
			{
				string text = time.ToString(culture);
				Console.WriteLine(string.Format("{0, -35} {1}", entry, text));
			}
			else
				Console.WriteLine(string.Format("{0, -35} {1}", entry, "PARSING ERROR!"));
		}
	}
}
Nota: para analisar a string de data e hora, é possível usar DateTime.Parse método também, que gera exceção se o formato estiver incorreto ou não for suportado.

 

Resultado:

2019-08-18T07:36:13.5344729+01:00   08/18/2019 07:36:13

2019-08-18T07:36:13+01:00           08/18/2019 07:36:13
2019-08-18T07:36:13+01              08/18/2019 07:36:13
2019-08-18T07:36:13                 08/18/2019 07:36:13
2019-08-18T07:36+01:00              08/18/2019 07:36:00
2019-08-18T07:36+01                 08/18/2019 07:36:00
2019-08-18T07:36                    08/18/2019 07:36:00
2019-08-18T07+01:00                 PARSING ERROR!
2019-08-18T07+01                    PARSING ERROR!
2019-08-18T07                       PARSING ERROR!
2019-08-18                          08/18/2019 00:00:00

20190818T073613+01:00               PARSING ERROR!
20190818T073613+01                  PARSING ERROR!
20190818T0736+01:00                 PARSING ERROR!
20190818T0736+01                    PARSING ERROR!
20190818T07+01:00                   PARSING ERROR!
20190818T07+01                      PARSING ERROR!
20190818T07                         PARSING ERROR!
20190818                            PARSING ERROR!

--08-18                             PARSING ERROR!

2019-08-18T06:36:13Z                08/18/2019 07:36:13
2019-08-18T06:36Z                   08/18/2019 07:36:00
2019-08-18T06Z                      PARSING ERROR!
20190818T063613Z                    PARSING ERROR!
20190818T0636Z                      PARSING ERROR!
20190818T06Z                        PARSING ERROR!

2019-W34-0                          PARSING ERROR!
2019-W34                            PARSING ERROR!
2019-230                            PARSING ERROR!
Nota: os valores de data e hora são analisados para a hora local, o que foi mostrado no resultado - leia mais sobre o sufixo Z aqui. 

2. Exemplo de formato personalizado

Existem outras maneiras de usar formatos personalizados para analisar a seq√ľ√™ncia de data e hora tamb√©m.

Quando a an√°lise padr√£o falhou e temos certeza de que usamos o formato de data e hora correto, podemos definir casos adicionais que s√£o aceitos.

As datas abaixo foram copiadas do exemplo acima - portanto, é fácil detectar quais não são compatíveis com o Método Parse.

using System;
using System.Globalization;

public class Program
{
	public static void Main()
	{
		string[,] dates = {
			// FORMAT                    TEXT

			{ "yyyy-MM-ddTHH:mm:sszzz",   "2019-08-18T07:36:13+01:00" },
			{ "yyyy-MM-ddTHH:mm:sszz",    "2019-08-18T07:36:13+01"    },
			{ "yyyy-MM-ddTHH:mm:ss",      "2019-08-18T07:36:13"       },
			{ "yyyy-MM-ddTHH:mmzzz",      "2019-08-18T07:36+01:00"    },
			{ "yyyy-MM-ddTHH:mmzz",       "2019-08-18T07:36+01"       },
			{ "yyyy-MM-ddTHH:mm",         "2019-08-18T07:36"          },
			{ "yyyy-MM-ddTHHzzz",         "2019-08-18T07+01:00"       },
			{ "yyyy-MM-ddTHHzz",          "2019-08-18T07+01"          },
			{ "yyyy-MM-ddTHH",            "2019-08-18T07"             },
			{ "yyyy-MM-dd",               "2019-08-18"                },

			{ "yyyyMMddTHHmmsszzz",       "20190818T073613+01:00"     },
			{ "yyyyMMddTHHmmsszz",        "20190818T073613+01"        },
			{ "yyyyMMddTHHmmzzz",         "20190818T0736+01:00"       },
			{ "yyyyMMddTHHmmzz",          "20190818T0736+01"          },
			{ "yyyyMMddTHHzzz",           "20190818T07+01:00"         },
			{ "yyyyMMddTHHzz",            "20190818T07+01"            },
			{ "yyyyMMddTHH",              "20190818T07"               },
			{ "yyyyMMdd",                 "20190818"                  },

			{ "--MM-dd",                  "--08-18"                  },

			{ "yyyy-MM-ddTHH:mm:ssZ",     "2019-08-18T06:36:13Z"      },
			{ "yyyy-MM-ddTHH:mmZ",        "2019-08-18T06:36Z"         },
			{ "yyyy-MM-ddTHHZ",           "2019-08-18T06Z"            },

			{ "yyyyMMddTHHmmssZ",         "20190818T063613Z"          },
			{ "yyyyMMddTHHmmZ",           "20190818T0636Z"            },
			{ "yyyyMMddTHHZ",             "20190818T06Z"              }
		};

		CultureInfo culture = CultureInfo.InvariantCulture;
		int length = dates.GetLength(0);

		for (int i = 0; i < length; ++i)
		{
			string format = dates[i, 0];
			string text = dates[i, 1];

			DateTime time = DateTime.ParseExact(text, format, culture, DateTimeStyles.None);
			Console.WriteLine(string.Format("{0, -35} {1}", text, time.ToString(culture)));
		}
	}
}

Resultado:

2019-08-18T07:36:13+01:00           08/18/2019 07:36:13
2019-08-18T07:36:13+01              08/18/2019 07:36:13
2019-08-18T07:36:13                 08/18/2019 07:36:13
2019-08-18T07:36+01:00              08/18/2019 07:36:00
2019-08-18T07:36+01                 08/18/2019 07:36:00
2019-08-18T07:36                    08/18/2019 07:36:00
2019-08-18T07+01:00                 08/18/2019 07:00:00
2019-08-18T07+01                    08/18/2019 07:00:00
2019-08-18T07                       08/18/2019 07:00:00
2019-08-18                          08/18/2019 00:00:00

20190818T073613+01:00               08/18/2019 07:36:13
20190818T073613+01                  08/18/2019 07:36:13
20190818T0736+01:00                 08/18/2019 07:36:00
20190818T0736+01                    08/18/2019 07:36:00
20190818T07+01:00                   08/18/2019 07:00:00
20190818T07+01                      08/18/2019 07:00:00
20190818T07                         08/18/2019 07:00:00
20190818                            08/18/2019 00:00:00

--08-18                             08/18/2019 00:00:00

2019-08-18T06:36:13Z                08/18/2019 07:36:13
2019-08-18T06:36Z                   08/18/2019 07:36:00
2019-08-18T06Z                      08/18/2019 07:00:00

20190818T063613Z                    08/18/2019 07:36:13
20190818T0636Z                      08/18/2019 07:36:00
20190818T06Z                        08/18/2019 07:00:00
Nota: os valores de data e hora são analisados para a hora local, o que foi mostrado no resultado - leia mais sobre o sufixo Z aqui. 

Veja também:

  1. ISO 8601 - What is Z in date time format yyyy-MM-ddTHH:mm:ssZ

Referências:

  1. ISO 8601 - Wikipedia
  2. ISO week date - Wikipedia
  3. DateTime.ParseExact Method - Microsoft Docs
Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.