简体   繁体   English

c# 自定义日期格式

[英]c# custom date format

I would like to have the word "day(s)" displayed in the output.我想在 output 中显示单词“day(s)”。 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 是一个 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:我之前一直在为此苦苦挣扎,并且总是以使用 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.当然,您可以让它更高级,并且仅在时间跨度中有 1 天或更多天时才显示“天”,而且您可以动态 append 和天数大于 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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