Languages
[Edit]
PT

C# / .NET - converter ISO 8601 para DateTime

3 points
Created by:
Alyona
1140

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
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join