VSMod_AriasServerUtils/AriasServerUtils/TimeUtil.cs

72 lines
2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace AriasServerUtils
{
public static class TimeUtil
{
private static readonly Dictionary<char, int> TimeUnits = new()
{
{ 's', 1 }, // seconds
{ 'm', 60 }, // minutes
{ 'h', 3600 }, // hours
{ 'd', 86400 }, // days
{ 'w', 604800 }, // weeks
{ 'M', 2592000 }, // months (approx. 30 days)
{ 'y', 31536000 } // years (365 days)
};
public static long DecodeTimeNotation(string input)
{
if (string.IsNullOrWhiteSpace(input)) return 0;
long totalSeconds = 0;
int number = 0;
foreach (char c in input)
{
if (char.IsDigit(c))
{
number = number * 10 + (c - '0');
}
else if (TimeUnits.TryGetValue(c, out int unitSeconds))
{
totalSeconds += number * unitSeconds;
number = 0;
}
else
{
throw new FormatException($"Invalid time unit: {c}");
}
}
return totalSeconds;
}
public static string EncodeTimeNotation(long seconds)
{
if (seconds <= 0) return "0s";
var result = new List<string>();
foreach (var (unit, unitSeconds) in TimeUnits.OrderByDescending(u => u.Value))
{
long value = seconds / unitSeconds;
if (value > 0)
{
result.Add($"{value}{unit}");
seconds %= unitSeconds;
}
}
return string.Join("", result);
}
public static long GetUnixEpochTimestamp()
{
return DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
}
}