summaryrefslogtreecommitdiff
path: root/Util/Extensions.cs
blob: bbf9a12335d843d0faddc2d0db0e72c4be5f4d40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace HyperBooru.Util;

public static class Extensions {
    public static readonly string[] MagnitudeOrders = new[] {
        "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"
    };

    public static DateTime? TryParseDateTimeUtc(this string s) {
        bool success = DateTime.TryParse(s, out var dateTime);
        return success ? DateTime.SpecifyKind(dateTime, DateTimeKind.Utc) : null;
    }

    public static string ToBytesSI(this long x) {
        var exp = (int) Math.Log10(x);
        var suffix = MagnitudeOrders.ElementAtOrDefault(exp / 3 - 1);
        if(suffix is null)
            return x.ToString();
        double n = x / Math.Pow(10, exp / 3 * 3);
        return $"{Math.Round(n, 2 - (exp % 3))} {suffix}B";
    }

    public static string ToStringHumanReadable(this TimeSpan t) {
        if(t.TotalMilliseconds < 1000)
            return string.Format("{0:0}ms", t.TotalMilliseconds);
        if(t.TotalSeconds < 60)
            return string.Format("{0:0.00}s", t.TotalSeconds);
        if(t.TotalMinutes < 60)
            return string.Format("{0:0}m{0:0}s", t.TotalMinutes, t.Seconds);
        if(t.TotalHours < 24)
            return string.Format("{0:0}h{0:0}m", t.TotalHours, t.Minutes);
        return string.Format("{0:0.00}d", t.TotalDays);
    }
}