简体   繁体   English

动态时间跨度格式字符串

[英]Dynamic timespan format string

I want to set my TimeSpan format string dynamically. 我想动态设置我的TimeSpan格式字符串。 It means if the time span value is negative format string should be different from positive one. 这意味着如果时间跨度值为负格式,则字符串应与正数字符串不同。 the point that when I want to set format string I don't know the value of TimeSpan ! 当我想设置格式字符串时,我不知道TimeSpan的价值!

For example: I want to have -03:01:01 for negative timespan and 003:01:01 for positive value 例如:我希望-03:01:01为负时间跨度,003:01:01为正值

the code is 代码是

columns.Add(new TimeSpanColumnInfo(col.PropertyName, col.TitlePersian, col.TitleEnglish, "ddd\\:hh\\:mm"));

witch third arguments is formatstring 第三个参数是formatstring

Your question still isn't clear but if you have a TimeSpan object called t you can conditionally choose a format string by doing the following: 您的问题仍然不明确,但如果您有一个名为tTimeSpan对象,则可以通过执行以下操作有条件地选择格式字符串:

string format = t < TimeSpan.Zero ? @"\-dd\:hh\:mm" : @"ddd\:hh\:mm";

If you really need to specify the format in advance of knowing the value of t (questionable), then you could change your method signature to accept a Func<TimeSpan, string> and pass in the following as an argument: 如果您确实需要在知道t (可疑)的值之前指定格式,那么您可以更改方法签名以接受Func<TimeSpan, string>并将以下内容作为参数传递:

o => o < TimeSpan.Zero ? @"\-dd\:hh\:mm" : @"ddd\:hh\:mm"

More info on Func<T, TResult> . 有关Func<T, TResult>更多信息。

It sounds like you're looking for something like the section separator . 听起来你正在寻找类似分隔符的东西。

string s = someNumber.ToString("00;(00)");

In the above example, positive values are output with two digits and negative values are output with two digits wrapped in parenthesis. 在上面的示例中,正值以两位数输出,负值以两位数字括在括号中输出。

Unfortunately, the section separator is only valid for custom numeric formats. 不幸的是,节分隔符仅对自定义数字格式有效。 The custom timespan formats do not include a section separator. 自定义时间跨度格式不包括节分隔符。

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

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