How to show timezone along with datetime

85 views Asked by At

In my application i have a datetime variable which i save in db after converting to UTC. I have used DateTime.UTCNow to convert to UTC. We get some real time information and which is in CET. Now while sending this back to the client application I would like to mention timezone also. It means for UTC Z and for CET +02:00. How can I include timezone to a datetime. Below

DateTime utcNow = DateTime.UtcNow;

var unspecifiedDateTime = DateTime.SpecifyKind(utcNow, DateTimeKind.Unspecified);
var tzi = TZConvert.GetTimeZoneInfo("Europe/Brussels");

var final = TimeZoneInfo.ConvertTimeToUtc(unspecifiedDateTime, tzi);

But i didnt get in to the specific format i needed..i never worked on timezone and its bit complicated for me

I need something like this for UTC "2023-10-18T16:47:14.08Z" or "2023-10-18T16:47:14.08+00:00" and in CET 2023-10-18T16:47:14.08+02:00. this way client application can understand

1

There are 1 answers

0
Erdit On

For you to represent the DateTime in this format you'd like, you can just use ToString with a custom format string, and also some logic to get the timezone offset.

DateTime utcNow = DateTime.UtcNow;

string utcFormat1 = utcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); //2023-10-18T16:47:14.08Z
string utcFormat2 = utcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz"); //2023-10-18T16:47:14.08+00:00

Which outputs:

UTC Format 1: 2023-10-19T14:10:33.430Z
UTC Format 2: 2023-10-19T14:10:33.430+00:00

For CET format, you convert the UTC DateTime to CET using TimeZoneInfo, then get CET time by using ConvertTimeFromUtc.

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime cetTime = TimeZoneInfo.ConvertTimeFromUtc(utcNow, tzi);

Then you can just use ToString in the same way as we did before:

string cetFormat = cetTime.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz");

Finally giving you an output you desired:

CET Format: 2023-10-19T16:10:33.430+01:00

Learn more about what these format strings properly represent here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings