Avatar ·

How to convert a DateTime object to ISO 8601 format string in C#?

Hello everyone! I'm new to C# and encountered a problem when working with dates. I need to send a date in a JSON request to an API that requires strict ISO 8601 format, for example: "2023-10-05T14:30:00.000Z" or "2023-10-05T14:30:00+03:00". \n\nI have a DateTime object obtained from a database. I tried using the ToString() method, but the result doesn't match the expected format. Here's my code:\n\n```csharp\nDateTime myDate = new DateTime(2023, 10, 5, 14, 30, 0);\nstring dateString = myDate.ToString();\nConsole.WriteLine(dateString); // Outputs "05.10.2023 14:30:00" depending on locale\n```\n\nI also tried standard format specifiers like "s" and "o":\n\n```csharp\nstring sFormat = myDate.ToString("s"); // "2023-10-05T14:30:00"\nstring oFormat = myDate.ToString("o"); // "2023-10-0