I was reading this MSDocs article about DateTime-related format support https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support#support-for-the-iso-8601-12019-format
And I was trying to cast datetime to string with this format without colon in the timezone part:
2021-01-01T14:30:10 0030
I want to cast this datetimeoffset to string. I use this format:
yyyy-MM-ddTHH:mm:sszzz
But the output of the ToString("yyyy-MM-ddTHH:mm:sszzz") method is:
2021-01-01T14:30:10 00:30
It has colon (:) sign in timezone part. How can I cast it like '2021-01-01T14:30:10 0030'? (without colon in the timezone part)
Can I format the timezone part?
CodePudding user response:
It seems it's not possible (in .Net 6 at least) to get a format string for DateTimeOffset
to get the required representation. However, you can try combining two formats: date
(which is of typeDateTimeOffset
) and ints Offset
(of type TimeSpan
)
string result = $"{date:yyyy-MM-ddTHH:mm:sszz}{date.Offset:mm}";
Here we combine
date:date:yyyy-MM-ddTHH:mm:sszz
-date
with Offset up to hoursdate.Offset:mm
-Offset
minutes