fasadat
fasadat

Reputation: 1045

Dynamic timespan format string

I want to set my TimeSpan format string dynamically. 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!

For example: I want to have -03:01:01 for negative timespan and 003:01:01 for positive value

the code is

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

witch third arguments is formatstring

Upvotes: 0

Views: 885

Answers (2)

Ant P
Ant P

Reputation: 25221

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:

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:

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

More info on Func<T, TResult>.

Upvotes: 2

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

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.

Upvotes: 0

Related Questions