Created
October 4, 2020 20:33
-
-
Save tolgabalci/495705370f821effcbaf1c17bb0121a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace tests | |
{ | |
public static class ExtensionMethods | |
{ | |
/// <summary> | |
/// Returns the TimeSpan text in a concise way | |
/// using at most two of the DateTime components. | |
/// </summary> | |
/// <returns> | |
/// Example Return Strings | |
/// 2 days and 4 hours ago | |
/// 1 day ago (if hours are zero) | |
/// 1 hour abd 14 minutes ago | |
/// 25 minutes and 15 seconds ago | |
/// 30 seconds ago (if minutes are zero) | |
/// </returns> | |
public static string ToConciseString(this TimeSpan timeSpan) | |
{ | |
if (timeSpan.TotalMilliseconds == 0) | |
{ | |
return "just now"; | |
} | |
List<string> s = new List<string>(); | |
if (timeSpan.Days == 1) s.Add($"{timeSpan.Days} day"); | |
if (timeSpan.Days > 1) s.Add($"{timeSpan.Days} days"); | |
if (timeSpan.Hours == 1) s.Add($"{timeSpan.Hours} hour"); | |
if (timeSpan.Hours > 1) s.Add($"{timeSpan.Hours} hours"); | |
if (timeSpan.Days < 1) | |
{ | |
if (timeSpan.Minutes == 1) s.Add($"{timeSpan.Minutes} minute"); | |
if (timeSpan.Minutes > 1) s.Add($"{timeSpan.Minutes} minutes"); | |
if (timeSpan.Hours < 1) | |
{ | |
if (timeSpan.Seconds == 1) s.Add($"{timeSpan.Seconds} second"); | |
if (timeSpan.Seconds > 1) s.Add($"{timeSpan.Seconds} seconds"); | |
if (timeSpan.Minutes < 1) | |
{ | |
if (timeSpan.Milliseconds == 1) s.Add($"{timeSpan.Milliseconds} millisecond"); | |
if (timeSpan.Milliseconds > 1) s.Add($"{timeSpan.Milliseconds} milliseconds"); | |
} | |
} | |
} | |
return string.Join(" and ", s) + " ago"; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(new TimeSpan(2, 5, 45, 30, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(2, 1, 45, 30, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(1, 5, 45, 30, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(0, 5, 45, 30, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(0, 0, 45, 30, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(0, 0, 0, 30, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(0, 0, 0, 0, 800).ToConciseString()); | |
Console.WriteLine(new TimeSpan(0, 0, 0, 0, 0).ToConciseString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment