/// <summary>
/// 时间转换类
/// </summary>
public class TimeConverter
{
/// <summary>
/// 本地时间转成 - UTC时间、距1970年的毫秒数
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long DateTimeToMilliseconds(DateTime time)
{
try
{
if (time.Year < 1970 || time.Year > 2030)
{
time = new DateTime(2000, time.Month, time.Day, time.Hour, time.Minute, time.Second);
}
return (long)(time.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
}
catch (ArgumentOutOfRangeException argu)
{
Console.WriteLine(argu.Message);
}
catch (ArgumentException argu2)
{
Console.WriteLine(argu2.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
}
/// <summary>
/// 本地时间转成 - UTC时间、距1970年的秒数
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long DateTimeToSeconds(DateTime time)
{
try
{
if (time.Year < 1970 || time.Year > 2030)
{
time = new DateTime(2000, time.Month, time.Day, time.Hour, time.Minute, time.Second);
}
return (long)(time.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
}
catch (ArgumentOutOfRangeException argu)
{
Console.WriteLine(argu.Message);
}
catch (ArgumentException argu2)
{
Console.WriteLine(argu2.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
}
/// <summary>
/// UTC距1970年毫秒数 - 转成本地时间
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
public static DateTime MillisecondsToDateTime(long milliseconds)
{
try
{
DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
if (time.Year < 1970 || time.Year > 2030)
{
time = new DateTime(2000, time.Month, time.Day, time.Hour, time.Minute, time.Second);
}
return time;
}
catch (ArgumentOutOfRangeException argu)
{
Console.WriteLine(argu.Message);
}
catch (ArgumentException argu2)
{
Console.WriteLine(argu2.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return DateTime.Now;
}
/// <summary>
/// UTC距1970年秒数 - 转成本地时间
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public static DateTime SecondsToDateTime(long seconds)
{
try
{
DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds).ToLocalTime();
if (time.Year < 1970 || time.Year > 2030)
{
time = new DateTime(2000, time.Month, time.Day, time.Hour, time.Minute, time.Second);
}
return time;
}
catch (ArgumentOutOfRangeException argu)
{
Console.WriteLine(argu.Message);
}
catch (ArgumentException argu2)
{
Console.WriteLine(argu2.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return DateTime.Now;
}
}