Input value is only like this in string value and nothing else: P0DT3H40M0S
This indicates travel time and needs to be converted to hours and minutes.
D signifies Day, T is Time (right part signifies Time, above sample was: 3 Hours And 40 Minutes and 0 Seconds. H-hours, M-Minutes, S-Seconds)
If there's a value in D, eg. P1DT3H40M0S
- this already signifies 1 Day and 3 Hours and 40 minutes and 0 Seconds, so output should be 27 Hours and 40 minutes. How do i get the values for Days, Hours and minutes using Regex? or can i use substring? my problem is if there were 2 digit Days and Hours, substring won't work. i need to get the numbers leftside the D, H and M.
Asked
Active
Viewed 930 times
-2

alomegah
- 117
- 1
- 1
- 7
-
3You could use Noda Time, which will parse that into a `Period` object very easily... you'd then normalize it yourself. – Jon Skeet Jul 05 '17 at 07:40
-
@alomegah you don't need a regex, you can use TimeSpan.ParseExact. The resulting object will have a day portion but that doesn't matter in calculations. You can use custom formatting to display the timespan as total hours + minutes instead of days, hours etc – Panagiotis Kanavos Jul 05 '17 at 08:09
1 Answers
-1
You can use TimeSpan.ParseExact to parse this string into a TimeSpan
var pattern=@"\Pd\D\Th\Hm\Ms\S";
var ts = TimeSpan.ParseExact("P01DT3H40M0S",pattern,CultureInfo.InvariantCulture);
You can use the TimeSpan object in calculations. It supports addition, subtraction and comparison.
You can extract the total duration in hours using TotalHours. In this case, this will return 27.6666666
. You can get the whole hours just by casting to int, (int)ts.TotalHours
will return 27
.
Copying from one of Jon Skeet's answers you can format the string as hours/minutes by using the truncated TotalHours and the Minutes, Seconds component:
String.Format("{0}:{1}:{2}",(int)ts.TotalHours,ts.Minutes,ts.Seconds)
This will return 27:40:0

Panagiotis Kanavos
- 120,703
- 13
- 188
- 236