using System.ComponentModel;
using System.Reflection;
namespace YD_WeChatApplet.Api.Utilities
{
///
/// 工具
///
public static class Tool
{
///
/// 获取枚举描述
///
///
///
public static string GetDescription(this Enum value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), "Enum value cannot be null");
}
// 获取字段信息
FieldInfo field = value.GetType().GetField(value.ToString());
if (field == null)
{
// 如果字段信息为空,返回默认的描述
return "";
}
// 获取 DescriptionAttribute 特性
var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
var attribute = attributes.FirstOrDefault() as DescriptionAttribute;
// 如果特性为空,返回空字符串
return attribute?.Description ?? "";
} ///
/// 将秒数转换为 "X分钟Y秒" 的格式
///
/// 秒数
/// 格式化后的字符串,如 "3分钟20秒"
public static string ToMinutesSeconds(this int seconds)
{
if (seconds < 0)
throw new ArgumentException("秒数不能为负数", nameof(seconds));
int minutes = seconds / 60;
int remainingSeconds = seconds % 60;
return $"{minutes}分钟{remainingSeconds}秒";
}
///
/// 将秒数转换为 "X分钟Y秒" 的格式(适用于浮点数)
///
/// 秒数
/// 格式化后的字符串,如 "3分钟20秒"
public static string ToMinutesSeconds(this double seconds)
{
if (seconds < 0)
throw new ArgumentException("秒数不能为负数", nameof(seconds));
int totalSeconds = (int)Math.Round(seconds);
return totalSeconds.ToMinutesSeconds();
}
///
/// 转换为 Unix 时间戳(秒)
///
public static long ToUnixTimestamp(this DateTime dateTime)
{
return (long)(dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
}
///
/// 转换为 Unix 时间戳(毫秒)
///
public static long ToUnixTimestampMilliseconds(this DateTime dateTime)
{
return (long)(dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
}
}
}