简体   繁体   中英

c# custom date format

I would like to have the word "day(s)" displayed in the output. I've tried putting escape characters in front of just the "-", in front of all the characters and spaces in "days". Any ideas or pointers.

This is the line I'm working with, totalTimeInRoom is a TimeSpan:

totalTimeInRoom.ToString(@"dd\.hh\:mm\:ss"); 

EDIT: Just tried this, no luck:

totalTimeInRoom.ToString(@"dd \"Days(s)\" \- hh\:mm\:ss");

As explained here , you can use single quote characters to embed a literal string in your custom date format:

totalTimeInRoom.ToString("dd' Day(s) 'hh':'mm':'ss");

I've struggled with this before and always ended up "cheating" using String.Format:

// extend with minutes, seconds etc. if needed
var text = String.Format ("{0} day(s), {1} hour(s)", totalTimeInRoom.Days, totalTimeInRoom.Hours);

Of course, you could make it much more advanced and only show 'days' if there's actually 1 or more days in the timespan and also instead of unconditionally using "day(s)" you can dynamically append an 's' when the number of days is more than 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