datetime conversion to specific format

Nehemiah Cheburet 21 Reputation points
2021-04-03T23:04:11.387+00:00

i am finding a challenge to convert to this date format "2021-05-05T21:03:09+00:00". I have tried the following and it is not working:
DateTime now = DateTime.Now;

Console.WriteLine(now.ToString("o"));
it produces the following:
2021-04-03T22:49:56.2248862+00:00

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Igor 6 Reputation points
    2021-04-04T00:25:10.317+00:00

    DateTime localDate = DateTime.Now;
    string Current_Date_Time;
    Current_Date_Time = localDate.ToString("yyyy-MM-ddTHH:mm:ss+00:00");

    Maybe this will work.

    1 person found this answer helpful.
    0 comments No comments

  2. Davin Mickelson 116 Reputation points
    2021-04-04T05:57:57.093+00:00

    I like Igor's above.

    Console.WriteLine($"{DateTime.Now:yyyy-MM-ddTHH:mm:ss+00:00}");
    
    1 person found this answer helpful.

  3. Karen Payne MVP 35,036 Reputation points
    2021-04-04T00:25:18.843+00:00

    See if helps and with that explore various methods available.

    string dateToConvert = "2021-05-05T21:03:09+00:00";
    
    if (DateTimeOffset.TryParse(dateToConvert, out var result))
    {
        Console.WriteLine($"{result}");
        Console.WriteLine($"{result} {result:O} - {result.ToLocalTime()}");
        Console.WriteLine($"{result.ToLocalTime()}");
    }
    else
    {
        Console.WriteLine("Invalid");
    }
    

    See also NodaTime

    0 comments No comments