using System; using System.Collections.Generic; using System.Text; namespace Common { /// /// datetime数据类型拓展 /// public static class DateTimeExtension { /// ///将一个时间转换为秒级时间戳 /// /// 时间 /// public static long ToTimeStampSeconds(this DateTime datetime) { return (long)Math.Round((datetime.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalSeconds); } /// ///将一个时间转换为毫秒级时间戳 /// /// /// public static long ToTimeStampMilliSeconds(this DateTime datetime) { return (long)Math.Round((datetime.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalMilliseconds); } /// /// 获取标准时间戳 秒级 /// /// /// public static long ToTimeStamp(this DateTime datetime) { return ToTimeStampSeconds(datetime); } /// /// 将时间转换为时间字符串编码 yyyyMMddHHmmssffff /// /// /// public static string ToTimeStr(this DateTime datetime) { return datetime.ToString("yyyyMMddHHmmssffff"); } /// /// 判断时间是否大于1970年的有效时间 /// /// /// public static bool IsValidTime(this DateTime dateTime) { if (dateTime.Date >= DateTime.Parse("1970-1-1")) return true; else return false; } /// /// 获时间一天中的开始时间 /// /// public static DateTime GetDayStartTime(this DateTime dateTime) { return dateTime.Date; } /// /// 获取时间一天的结束时间 /// /// /// public static DateTime GetDateEndTime(this DateTime dateTime) { return dateTime.Date.AddDays(1).AddSeconds(-1); } /// /// 获取时间周的星期一的时间 /// /// /// public static DateTime GetWeekStartTime(this DateTime dateTime) { return dateTime.GetWeekOfDayTime(1); } /// /// 获取时间周的周日 /// /// /// public static DateTime GetWeekEndTime(this DateTime dateTime) { return dateTime.GetWeekOfDayTime(7); } /// /// 获取时间周的指定周几时间 /// /// /// 周几 1 2 3 4 5 6 7 /// public static DateTime GetWeekOfDayTime(this DateTime dateTime, int Day) { if (Day < 1) Day = 1; if (Day > 7) Day = (int)dateTime.DayOfWeek; return dateTime.Subtract(new TimeSpan(dateTime.DayOfWeek - (DayOfWeek)Day, 0, 0, 0)).Date; } /// /// 获取时间月度开始时间 /// /// /// public static DateTime GetMonthStartTime(this DateTime dateTime) { return new DateTime(dateTime.Year,dateTime.Month,1).Date; } /// /// 获取一个月度的结束时间 /// /// /// public static DateTime GetMonthEndTime(this DateTime dateTime) { return dateTime.GetMonthStartTime().AddMonths(1).AddSeconds(-1); } /// /// 获取时间年度度开始时间 /// /// /// public static DateTime GetYearStartTime(this DateTime dateTime) { return new DateTime(dateTime.Year,1, 1).Date; } /// /// 获取一个年度的结束时间 /// /// /// public static DateTime GetYearEndTime(this DateTime dateTime) { return dateTime.GetYearStartTime().AddYears(1).AddSeconds(-1); } /// /// 获取零时区时间 /// /// 返回服务器零时区时间 public static DateTime GetUtcDateTime() { DateTime serverTime2 = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now, TimeZoneInfo.Local); return serverTime2; } private static DateTime dtMin = DateTime.Parse("1970-01-01"); /// /// 获取yyyy-MM-dd HH:mm:ss 时间格式 /// /// /// public static string ToSqlServerTimeString(this DateTime dt) { if (dt == dtMin) { return string.Empty; } return dt.ToString("yyyy-MM-dd HH:mm:ss"); } } }