Convert seconds to compound duration: Difference between revisions

Content added Content deleted
m (→‎version 2: added/changed comments and whitespace.)
Line 490:
 
=={{header|C sharp}}==
 
===C#: Standard method===
<lang csharp>using System;
using System.Collections.Generic;
Line 512 ⟶ 514:
}
return ;
}
Line 552 ⟶ 553:
6,000,000 seconds ==> 9 wk, 6 d, 10 h, 40 m
</pre>
 
===C#: Using the TimeSpan struct and query syntax===
{{libheader|System}}
{{libheader|System.Collections.Generic}}
{{libheader|System.Linq}}
{{works with|C sharp|6}}
<lang csharp>private static string ConvertToCompoundDuration(int seconds)
{
if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
if (seconds == 0) return "0 sec";
 
TimeSpan span = TimeSpan.FromSeconds(seconds);
int[] parts = {span.Days / 7, span.Days % 7, span.Hours, span.Minutes, span.Seconds};
string[] units = {" wk", " d", " hr", " min", " sec"};
 
return string.Join(", ",
from index in Enumerable.Range(0, units.Length)
where parts[index] > 0
select parts[index] + units[index]);
}</lang>
 
=={{header|C++}}==