82 lines
2.8 KiB
C#
82 lines
2.8 KiB
C#
namespace SJZY.Track.Application.Helpers;
|
|
|
|
public static class DateTimeHelper
|
|
{
|
|
/// <summary>
|
|
/// convert to a Unix timestamp from a DateTime object.
|
|
/// </summary>
|
|
/// <param name="dateTime">The DateTime object to convert to a Unix timestamp.</param>
|
|
/// <returns>The Unix timestamp as a long.</returns>
|
|
public static long ConvertToUnixTimestamp(DateTime dateTime)
|
|
{
|
|
return new DateTimeOffset(dateTime).ToUnixTimeSeconds();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Formats a DateTime object into a specified format.
|
|
/// </summary>
|
|
/// <param name="dateTime">The DateTime object to format.</param>
|
|
/// <param name="format">The format string.</param>
|
|
/// <returns>The formatted date string.</returns>
|
|
public static string FormatDateTime(DateTime dateTime, string format)
|
|
{
|
|
return dateTime.ToString(format);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 时区格式化
|
|
/// </summary>
|
|
/// <param name="timezone"></param>
|
|
/// <param name="format"></param>
|
|
/// <returns></returns>
|
|
public static string TimezoneFormat(double timezone, string format)
|
|
{
|
|
//时区是整数丢掉浮点数部分
|
|
return format.Replace("hh", ((int) timezone).ToString());
|
|
}
|
|
|
|
/// <summary>
|
|
/// 转换主数据中心类似GMT-09:00这种的时区为浮点数
|
|
/// </summary>
|
|
/// <param name="timeZone">分区</param>
|
|
/// <returns></returns>
|
|
/// <exception cref="ArgumentException"></exception>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将浮点数时区转换为GMT格式
|
|
/// 如果为null则返回"--"
|
|
/// </summary>
|
|
/// <param name="timezone"></param>
|
|
/// <returns></returns>
|
|
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")}";
|
|
}
|
|
}
|