Reputation: 135
I'm using .net 3.5 and I would like to find out if there is a way to use Regex.Replace to format TimeSpan components for user provided formats. Ideally the user could send several types of desired formats as arguments - e.g. HH:mm, hh:mm, dd:hh:mm, mm:ss and so on. The replace function would interrogate the user format and return the TimeSpan value in the desired format.
I've done a bit of digging and have come up with the below. It's not a solution, but will give you an idea of what I am trying to achieve.
// Sample Replace Pattern for TimeSpan
string pattern = @"(?<dd>\d{2}).(?<hh>\d{2}).(?<mm>\d{2})";
string replaceStr = @"{dd:hh:mm}";
var myRegEx = new Regex(pattern);
TimeSpan ts = new TimeSpan(3, 10,3, 22);
string dateResult = myRegEx.Replace(ts.ToString(), replaceStr);
Thanks - Glenn
Upvotes: 0
Views: 784
Reputation: 63065
You can use ToString method of TimeSpan As below , You don't need regex for this if I understood correctly
string dateResult = ts.ToString(@"dd\:hh\:mm");
if you have multiple formats then like below
HH:mm, hh:mm, dd:hh:mm, mm:ss
then replace input :
with \:
and apend @
to the begin
You can now use this format string to call ToString method of TimeSpan
Upvotes: 2