summaryrefslogtreecommitdiffstats
path: root/src/Tools.cs
blob: 8aaedc92de08a4d799f9d34505073a7025b1ea55 (plain) (blame)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Text.RegularExpressions;

namespace BlobBin;

public static class Tools
{
    public static string GetFilesDirectoryPath(bool createIfNotExists = false) {
        var filesDirectoryPath = Path.Combine(
            Directory.GetCurrentDirectory(),
            "AppData",
            "files"
        );
        if (createIfNotExists) Directory.CreateDirectory(filesDirectoryPath);
        return filesDirectoryPath;
    }

    public static TimeSpan ParseHumanTimeSpan(string dateTime) {
        var ts = TimeSpan.Zero;
        var currentString = "";
        var currentNumber = "";
        foreach (var ch in dateTime + ' ') {
            currentString += ch;
            if (Regex.IsMatch(currentString, @"^(years(\d|\s)|year(\d|\s)|y(\d|\s))", RegexOptions.IgnoreCase)) {
                ts = ts.Add(TimeSpan.FromDays(365 * int.Parse(currentNumber)));
                currentString = "";
                currentNumber = "";
            }

            if (Regex.IsMatch(currentString, @"^(weeks(\d|\s)|week(\d|\s)|w(\d|\s))", RegexOptions.IgnoreCase)) {
                ts = ts.Add(TimeSpan.FromDays(7 * int.Parse(currentNumber)));
                currentString = "";
                currentNumber = "";
            }

            if (Regex.IsMatch(currentString, @"^(days(\d|\s)|day(\d|\s)|d(\d|\s))", RegexOptions.IgnoreCase)) {
                ts = ts.Add(TimeSpan.FromDays(int.Parse(currentNumber)));
                currentString = "";
                currentNumber = "";
            }

            if (Regex.IsMatch(currentString, @"^(hours(\d|\s)|hour(\d|\s)|h(\d|\s))", RegexOptions.IgnoreCase)) {
                ts = ts.Add(TimeSpan.FromHours(int.Parse(currentNumber)));
                currentString = "";
                currentNumber = "";
            }

            if (Regex.IsMatch(currentString, @"^(mins(\d|\s)|min(\d|\s)|m(\d|\s))", RegexOptions.IgnoreCase)) {
                ts = ts.Add(TimeSpan.FromMinutes(int.Parse(currentNumber)));
                currentString = "";
                currentNumber = "";
            }

            if (Regex.IsMatch(currentString, @"^(secs(\d|\s)|sec(\d|\s)|s(\d|\s))", RegexOptions.IgnoreCase)) {
                ts = ts.Add(TimeSpan.FromSeconds(int.Parse(currentNumber)));
                currentString = "";
                currentNumber = "";
            }

            if (Regex.IsMatch(ch.ToString(), @"\d")) {
                currentNumber += ch;
                currentString = "";
            }
        }

        return ts;
    }
}