Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- public class HumanTimeFormat
- {
- [Flags]
- enum TimeItmes { none = 0, seconds = 1, minutes = 2, hours = 4, days = 8, years = 16 }
- private static readonly int year = 60 * 60 * 24 * 365;
- private static readonly int day = 60 * 60 * 24;
- private static readonly int hour = 60 * 60;
- private static readonly int minute = 60;
- private int[] _data = new int[5];
- private TimeItmes _timeItmes;
- HumanTimeFormat(int second)
- {
- while (second >= year)
- {
- second -= year;
- _data[0]++;
- _timeItmes |= TimeItmes.years;
- }
- while (second >= day)
- {
- second -= day;
- _data[1]++;
- _timeItmes |= TimeItmes.days;
- }
- while (second >= hour)
- {
- second -= hour;
- _data[2]++;
- _timeItmes |= TimeItmes.hours;
- }
- while (second >= minute)
- {
- second -= minute;
- _data[3]++;
- _timeItmes |= TimeItmes.minutes;
- }
- if (second > 0)
- {
- _data[4] = second;
- _timeItmes |= TimeItmes.seconds;
- }
- }
- public string ToString()
- {
- if (_timeItmes == TimeItmes.none)
- {
- return "now";
- }
- List<string> components = new();
- if ((_timeItmes & TimeItmes.years) == TimeItmes.years)
- {
- components.Add($"{_data[0]} year{(_data[0] > 1 ? "s" : "")}");
- }
- if ((_timeItmes & TimeItmes.days) == TimeItmes.days)
- {
- components.Add($"{_data[1]} day{(_data[1] > 1 ? "s" : "")}");
- }
- if ((_timeItmes & TimeItmes.hours) == TimeItmes.hours)
- {
- components.Add($"{_data[2]} hour{(_data[2] > 1 ? "s" : "")}");
- }
- if ((_timeItmes & TimeItmes.minutes) == TimeItmes.minutes)
- {
- components.Add($"{_data[3]} minute{(_data[3] > 1 ? "s" : "")}");
- }
- if ((_timeItmes & TimeItmes.seconds) == TimeItmes.seconds)
- {
- components.Add($"{_data[4]} second{(_data[4] > 1 ? "s" : "")}");
- }
- return components.Count switch
- {
- 1 => components[0],
- 2 => $"{components[0]} and {components[1]}",
- _ => $"{string.Join(", ", components.Take(components.Count - 1))} and {components[^1]}"
- };
- }
- public static string formatDuration(int seconds) => new HumanTimeFormat(seconds).ToString();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement