1

This is my input:

55

This is my desired output:

PT55H

Is there a built in class in C# that converts a timespan as: TimeSpan.TryParse(55) or as a string "55" with hours into an ISO8601 formatted string?

pb2q
  • 58,613
  • 19
  • 146
  • 147
Codeman
  • 12,157
  • 10
  • 53
  • 91

2 Answers2

1

You can convert a number to a TimeSpan with the static TimeSpan.FromHours method. For example var ts = TimeSpan.FromHours(55.0);.

If you always want the time represented with hours only, in the ISO system, maybe you can simply say var isostring = String.Format("PT{0}H", ts.TotalHours);.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • this would work but I want something generic for any timespan – Codeman Sep 24 '12 at 19:49
  • But doesn't it work for any time span? I thought you wanted an hour-only format. Like `PT55H` (55 hours) instead of `P2DT7H` (2 days and 7 hours). – Jeppe Stig Nielsen Sep 24 '12 at 19:56
  • Ideally, I would like to have hours-only, but with my requirement for being generic, it seems like I have no choice but to do the string handling myself, or allow it to use P2DT7H formatting.' – Codeman Sep 24 '12 at 20:01
  • For any `TimeSpan ts` (which shouldn't be negative), my `String.Format("PT{0}H", ts.TotalHours)` gives a PT followed by a number of hours (possibly with decimals), followed by an H. You could specify the number of decimals, or the decimal separator character if you wanted. – Jeppe Stig Nielsen Sep 24 '12 at 20:06
0

Coworker just found this for me:

TimeSpan start = new TimeSpan(int.Parse(txtStartHours.Text), 0, 0); 
durationNode.Element("StartTime").Value = XmlConvert.ToString(start); 

It seems to convert it to PT2D7H, but since I'm using XMLConvert.ToTimeSpan().TotalHours elsewhere, it shouldn't cause any problems!

Codeman
  • 12,157
  • 10
  • 53
  • 91