using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IoTIntegrationPlatform.Common { /// /// 时间公共类 /// public static class TimeHelper { /// /// 相差秒 /// /// /// /// public static double DiffSeconds(DateTime startTime, DateTime endTime) { TimeSpan secondSpan = new TimeSpan(endTime.Ticks - startTime.Ticks); return secondSpan.TotalSeconds; } /// /// 相差分钟数 /// /// /// /// public static double DiffMinutes(DateTime startTime, DateTime endTime) { TimeSpan minuteSpan = new TimeSpan(endTime.Ticks - startTime.Ticks); return minuteSpan.TotalMinutes; } /// /// 相差小时 /// /// /// /// public static double DiffHours(DateTime startTime, DateTime endTime) { TimeSpan hoursSpan = new TimeSpan(endTime.Ticks - startTime.Ticks); return hoursSpan.TotalHours; } /// /// 相差天数 /// /// /// /// public static double DiffDays(DateTime startTime, DateTime endTime) { TimeSpan daysSpan = new TimeSpan(endTime.Ticks - startTime.Ticks); return daysSpan.TotalDays; } /// /// 相差月数 /// /// /// /// public static double DiffMonths(DateTime startTime, DateTime endTime) { int months = (endTime.Year - startTime.Year) * 12 + endTime.Month - startTime.Month; if (startTime.Day > endTime.Day) months--; // 如果第一个日期的日大于第二个日期的日,则减去一个月 return months; } /// /// 获取当前时间戳 /// /// public static long GetCurrentTimestamp() { DateTimeOffset currentTime = DateTimeOffset.Now; long timestamp = currentTime.ToUnixTimeSeconds(); return timestamp; } /// /// 获取当前时间戳[毫秒] /// /// /// public static long GetCurrentTimestampTicks() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long t = Convert.ToInt64(ts.TotalMilliseconds); return t; } /// /// 时间转时间戳[毫秒] /// /// /// public static long DateToTimestampTicks(DateTime date) { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));//当地时区 TimeSpan ts = date - startTime; long timestamp = Convert.ToInt64(ts.TotalSeconds); return timestamp; } /// /// 某天的开始 /// /// /// public static DateTime DayOfZeroSeconds(DateTime datetime) { return datetime.AddDays(1 - datetime.Day).Date; } /// /// 某天的最后一秒 /// /// /// public static DateTime DayOfLastSeconds(DateTime datetime) { return datetime.AddDays(1).AddSeconds(-1); } } }