How to get datetime based on timezone offset in c#?

Viewed 1350

In c#, I do this

DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss")

but it gets me the server time. However I also have the offset in this format for example "-04:00". How can I combine the offset to get the local time?

Thanks

3 Answers

If you mean that you want to get the server's system local time including offset, then use the DateTimeOffset.Now property. Then format it as desired.

DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss zzz")

The zzz specifier produces the offset as a string in the ISO 8601 extended format, that you asked for.

If what you mean is you have a UTC offset from elsewhere and you want to apply it to the current UTC time from the server, then do the following instead:

TimeSpan offset = TimeSpan.Parse("-04:00");
DateTimeOffset now = DateTimeOffset.UtcNow.ToOffset(offset);
string result = now.ToString("yyyy-MM-dd HH:mm:ss zzz");

This takes the current server time, and applies the ToOffset function to adjust to the offset you provided.

Do keep in mind though that an offset is not the same as a time zone. The offset you have might be the one for the current date and time, or it might be for some other date and time in that time zone. For example, US Eastern Time is UTC-4 during daylight saving time, but UTC-5 during standard time. See "Time Zone != Offset" in the timezone tag wiki.

This should work

DateTime.UtcNow.AddHours(DateTimeOffset.Parse("01/01/0001 00:00:00 -04:00").Offset.TotalHours).ToString("yyyy-dd-M--HH-mm-ss",CultureInfo. InvariantCulture);

Need to add the directive

using System.Globalization;

This worked.

DateTime.UtcNow.AddHours(DateTimeOffset.Parse("01/01/0001 00:00:00 -04:00").Offset.TotalHours).ToString("yyyy-dd-M--HH-mm-ss")
Related