简体   繁体   中英

Utcoffset formats in C#

var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Console.WriteLine(((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));

The above code is working fine. But I need to display offset like +05:00. Is there any way to achieve this format?

From the docs :

The custom TimeSpan format specifiers don't include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals.

So you have to escape character in your format string that is not listed in the above page, either by surrounding it with ' , or with a backslash, so:

utcOffset.ToString("hh':'mm")

However, you don't actually have to do this formatting yourself, if you format a DateTimeOffset , rather than TimeSpan . If you do this, you don't need all the "getting the UTC offset" mess either.

You just need the zzz Custom Format Specifier :

DateTimeOffset.Now.ToString("zzz")

You don't need all of the TimeZone stuff.

Instead of using TimeZone to look up the timezone from DateTime.Now , you can use DateTimeOffset.Now with the zzz format string and CultureInfo.InvariantCulture to achieve this:

Console.WriteLine(DateTimeOffset.Now.ToString("HHmmzzz", System.Globalization.CultureInfo.InvariantCulture));
// outputs 1255+02:00

Try it online

If you just want the offset in that format, you can use "zzz" instead of "HHmmzzzz" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM