Search code examples
c#datetimeoffset

Datetimeoffset does not give the correct format


I have a variable start that holds the value "2020-07-01T00:00:00.000-05:00". Then I set another variable end to DateTimeOffset.Now but when I hover over it, it will tell me "9/1/2021 9:15:10 AM -05:00". I am wanting to have the variable end to have the same formatting as start does. Is there a way to have the formatting to display as it shows for variable start? I can't seem to find the answer I am looking for on the internet. Any pointers would be great.

var start = "2020-07-01T00:00:00.000-05:00"
var end = DateTimeOffset.Now

Solution

  • DateTimeOffset has ToString() overloads which accept format. You can try either one of the standard or build a custom one:

    Console.WriteLine(DateTimeOffset.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffK")); // exmaple output: 2021-09-01T16:55:13.815+02:00