简体   繁体   中英

C# Customize DateTime offset format in ToString()

Is it possible to produce an output like 2021-04-14 01:23:45.123456+0800 using DateTime.ToString() ?

I've tried to use .ToString("yyyy-MM-dd hh:mm:ss.ffffff") followed by some combination of z , zz , zzz , etc, but cannot seem to get the offset portion of the string to not contain the : .

ie it produces 2021-04-14 01:23:45.123456+08:00 , but I need the +08:00 to be +0800 .

There's not a custom timezone format that will give you the full timezone without the colon. The simplest solution (IMHO) is to just remove the colon and add the timezone manually:

dt.ToString("yyyy-MM-dd hh:mm:ss.ffffff") + 
  dt.ToString("zzz").Replace(":","");

Or you could add the time zone to the string format and remove the "last" colon:

s = dt.ToString("yyyy-MM-dd hh:mm:ss.ffffffzzz");
s = s.Remove(s.LastIndexOf(':'),1);

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