user1249190
user1249190

Reputation: 347

what is the standard way to display time span over 24 hours?

I am looking for a way to correctly display localized duration of time larger than 24 hours in C# and Delphi. I mean, the DateTime type often has such string function provided, but time span does not, why?

And I don't even know what is a correct format for non localized time span. e.g. for a duration of 2 days 10 hours 30 minutes. I found some would display such time span as 2.10:30:00 or 2:10:30:00 or 2 10:30:00.

Please help, thanks.

Upvotes: 2

Views: 981

Answers (2)

Reinier Torenbeek
Reinier Torenbeek

Reputation: 17383

You could follow ISO 8601, a PDF of the spec can be found here. See section 4.4.3 Duration

However, using the convention as lined out in this document looks fairly complicated to me, because according to this specification, you need to include context about when the time interval takes place:

The duration of a calendar year, a calendar month, a calendar week or a calendar day depends on its position in the calendar. Therefore, the exact duration of a nominal duration can only be evaluated if the duration of the calendar years, calendar months, calendar weeks or calendar days used are known.

If the actual moment at which the time span takes place is not relevant for your application, then maybe it would be good enough to forget about the year and month parts and just stick with the format nnDTnnHnnMnnS. That should not be too hard to achieve using the standard TimeSpan methods.

Update: Reading a bit further, this standard does not seem to be applicable to your problem after all:

Duration is used as a component in representations of time intervals and recurring time intervals, representation of duration as such is not facilitated by this International Standard.

I will just leave the answer here to avoid anybody else walking into this dead end like I did, or if you think 'sort of following a standard' is good enough...

Upvotes: 2

Matt
Matt

Reputation: 6963

For invariant culture (non localized):

myDateTime.ToString(CultureInfo.InvariantCulture)

Otherwise, just use myDateTime.ToShortDateString() or .ToLongDateString().. it will use :

System.Threading.Thread.CurrentThread.CurrentUICulture in that case..

or if you had something specific in mind, you could do

var myCulture = CultureInfo.GetCultureInfo("en-GB");
dt.ToString(myCulture);

EDIT For TimeSpans:

Example:

DateTime dt1 = new DateTime(2012, 7, 17, 12, 30, 0);
            DateTime dt2 = new DateTime(2012, 7, 18, 14, 40, 0);

            TimeSpan ts = dt2 - dt1;
            string s = ts.ToString("G", CultureInfo.InvariantCulture);

More examples here: http://msdn.microsoft.com/en-us/library/dd784379.aspx

EDIT 2:

More info on TimeSpan format strings: http://msdn.microsoft.com/en-us/library/ee372286.aspx

Upvotes: 2

Related Questions