namespace SJZY.Track.Application.Helpers; public static class DateTimeHelper { /// /// convert to a Unix timestamp from a DateTime object. /// /// The DateTime object to convert to a Unix timestamp. /// The Unix timestamp as a long. public static long ConvertToUnixTimestamp(DateTime dateTime) { return new DateTimeOffset(dateTime).ToUnixTimeSeconds(); } /// /// Formats a DateTime object into a specified format. /// /// The DateTime object to format. /// The format string. /// The formatted date string. public static string FormatDateTime(DateTime dateTime, string format) { return dateTime.ToString(format); } /// /// 时区格式化 /// /// /// /// public static string TimezoneFormat(double timezone, string format) { //时区是整数丢掉浮点数部分 return format.Replace("hh", ((int) timezone).ToString()); } /// /// 转换主数据中心类似GMT-09:00这种的时区为浮点数 /// /// 分区 /// /// public static float? ConvertTimeZoneToFloat(string timeZone) { if (string.IsNullOrEmpty(timeZone) || !timeZone.StartsWith("GMT")) { return null; } var sign = timeZone[3] == '+' ? 1 : -1; var parts = timeZone.Substring(4).Split(':'); var hours = int.Parse(parts[0]); var minutes = int.Parse(parts[1]); return sign * (hours + minutes / 60f); } /// /// 将浮点数时区转换为GMT格式 /// 如果为null则返回"--" /// /// /// public static string ConvertFloatToTimeZone(float? timezone) { if (timezone == null) return "--"; if (Math.Abs(timezone.Value - GlobalConst.NoneTrackTimeZone) < 0.01f) return "--"; if (Math.Abs(timezone.Value) < 0.01f) return "GMT +00:00"; // 将小数形式的小时转换为时区偏移量 var hours = (int) timezone.Value; // 提取整数部分作为小时 var minutes = (int) ((timezone.Value - hours) * 60); // 将小数部分乘以 60 转换为分钟 var offset = new TimeSpan(hours, minutes, 0); var timeZoneStr = offset.ToString(); var flag = timezone > 0f ? "+" : ""; return $"GMT {flag}{timeZoneStr.RemovePostFix(":00")}"; } }