using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace POSV.Utils { /// 时间帮助类 /// public class DateTimeUtils { /// 将时间转换成int32类型 /// public static int ToInt32(DateTime end , int defaultValue = 0) { //默认情况下以1970.01.01为开始时间计算 try { var startdate = new DateTime(1970 , 1 , 1 , 0 , 0 , 0); // TimeSpan seconds = end.AddDays(1) - startdate; var seconds = end - startdate; defaultValue = Convert.ToInt32(seconds.TotalSeconds); } catch (Exception) { // ignored } return defaultValue; } /// 将string类型的时间转换成int32 /// public static int ToInt32(string datetime , int defaultValue = 0) { if (!IsDataTime(datetime)) return defaultValue; var end = Convert.ToDateTime(datetime); return ToInt32(end , defaultValue); } public static bool IsDataTime(string source) { if (string.IsNullOrEmpty(source)) { return false; } DateTime d; return DateTime.TryParse(source , out d); } /// 将Int32类型的整数转换成时间 /// public static DateTime ToDateTime(int seconds) { var begtime = Convert.ToInt64(seconds) * 10000000;//100毫微秒为单位 var dt1970 = new DateTime(1970 , 1 , 1 , 0 , 0 , 0); var tricks1970 = dt1970.Ticks;//1970年1月1日刻度 var timeTricks = tricks1970 + begtime;//日志日期刻度 var dt = new DateTime(timeTricks);//转化为DateTime //DateTime enddt = dt.Date;//获取到日期整数 return dt; } /// 获取String类型的时间拼接,拼接到天 /// public static string GetPadDay(DateTime time) { var month = time.Month.ToString().PadLeft(2 , '0'); var day = time.Day.ToString().PadLeft(2 , '0'); var pad = string.Format("{0}{1}{2}" , time.Year , month , day); return pad; } /// 获取string类型拼接的时间 拼接到秒 /// public static string GetPadSecond(DateTime time) { var month = time.Month.ToString().PadLeft(2 , '0'); var day = time.Day.ToString().PadLeft(2 , '0'); var hour = time.Hour.ToString().PadLeft(2 , '0'); var minute = time.Minute.ToString().PadLeft(2 , '0'); var second = time.Second.ToString().PadLeft(2 , '0'); var pad = string.Format("{0}{1}{2}{3}{4}{5}" , time.Year , month , day , hour , minute , second); return pad; } /// 获取string类型拼接的时间 拼接到秒,但是不包括最早的2位 /// public static string GetPadSecondWithoutPrefix(DateTime time) { var month = time.Month.ToString().PadLeft(2 , '0'); var day = time.Day.ToString().PadLeft(2 , '0'); var hour = time.Hour.ToString().PadLeft(2 , '0'); var minute = time.Minute.ToString().PadLeft(2 , '0'); var second = time.Second.ToString().PadLeft(2 , '0'); var pad = string.Format("{0}{1}{2}{3}{4}{5}" , time.Year.ToString().Substring(2) , month , day , hour , minute , second); return pad; } /// 获取到毫秒的拼接 /// public static string GetPadMillSecond(DateTime time) { var month = time.Month.ToString().PadLeft(2 , '0'); var day = time.Day.ToString().PadLeft(2 , '0'); var hour = time.Hour.ToString().PadLeft(2 , '0'); var minute = time.Minute.ToString().PadLeft(2 , '0'); var second = time.Second.ToString().PadLeft(2 , '0'); var minSecond = time.Millisecond.ToString().PadLeft(3 , '0'); var pad = string.Format("{0}{1}{2}{3}{4}{5}{6}" , time.Year , month , day , hour , minute , second , minSecond); return pad; } /// 获取string类型拼接的时间 拼接到秒,但是不包括最早的2位,精确到毫秒 /// public static string GetPadMillSecondWithoutPrefix(DateTime time) { var month = time.Month.ToString().PadLeft(2 , '0'); var day = time.Day.ToString().PadLeft(2 , '0'); var hour = time.Hour.ToString().PadLeft(2 , '0'); var minute = time.Minute.ToString().PadLeft(2 , '0'); var second = time.Second.ToString().PadLeft(2 , '0'); var minSecond = time.Millisecond.ToString().PadLeft(3 , '0'); var pad = string.Format("{0}{1}{2}{3}{4}{5}{6}" , time.Year.ToString().Substring(2) , month , day , hour , minute , second , minSecond); return pad; } /// 获取两个时间之间经历的星期几 /// public static string GetWeekCross(DateTime begin , DateTime end) { if (begin.Date > end) { return ""; } var weekList = new List() { 0, 1, 2, 3, 4, 5, 6 }; if ((end.Date - begin.Date).TotalDays >= 7) { return string.Join("," , weekList); } var endWeek = (int)end.DayOfWeek; var beginWeek = (int)begin.DayOfWeek; if (beginWeek <= endWeek) { var containList = new List(); for (var i = beginWeek; i <= endWeek; i++) { containList.Add(weekList[i]); } return string.Join("," , containList); } var removeList = new List(); for (var i = endWeek + 1; i <= beginWeek - 1; i++) { removeList.Add(weekList[i]); } var target = weekList.Except(removeList).ToList(); return string.Join("," , target); } /// 获取某个时间的中文星期 /// public static string GetChineseWeekOfDay(DateTime time) { var dayOfWeek = (int)time.DayOfWeek; return GetWeekDays().FirstOrDefault(x => x.Key == dayOfWeek).Value; } /// 获取星期中的所有天数 /// public static Dictionary GetWeekDays() { var weekDict = new Dictionary { {0, "星期日"}, {1, "星期一"}, {2, "星期二"}, {3, "星期三"}, {4, "星期四"}, {5, "星期五"}, {6, "星期六"} }; return weekDict; } /// 获取某时间点第一天 /// public static DateTime GetFirstDayOfMonth(DateTime time) { return new DateTime(time.Year , time.Month , 1); } /// 获取某个时间点当月的最后一天 /// public static DateTime GetLastDayOfMonth(DateTime time) { return new DateTime(time.Year , time.Month , 1).AddMonths(1).AddDays(-1); } /// 获取某个时间点当年的第一天 /// public static DateTime GetFirstDayOfYear(DateTime time) { return new DateTime(time.Year , 1 , 1); } /// 获取某个时间点当年的最后一天 /// public static DateTime GetLastDayOfYear(DateTime time) { return new DateTime(time.Year + 1 , 1 , 1).AddDays(-1); } /// 判断某个时间是否为当月的第一天 /// public static bool IsFirstDayOfMonth(DateTime time) { var firstDay = GetFirstDayOfMonth(time); return firstDay.Date == time.Date; } /// 判断某个时间是否为当月的最后一天 /// public static bool IsLastDayOfMonth(DateTime time) { var lastDay = GetLastDayOfMonth(time); return lastDay.Date == time.Date; } /// 判断某个时间是否为当年的第一天 /// public static bool IsFirstDayOfYear(DateTime time) { var firstDay = GetFirstDayOfYear(time); return firstDay.Date == time.Date; } /// 判断某个时间是否为当年的最后一天 /// public static bool IsLastDayOfYear(DateTime time) { var lastDay = GetLastDayOfYear(time); return lastDay.Date == time.Date; } /// /// 设置本地电脑的年月日 /// /// /// /// public static void SetLocalDate(int year , int month , int day) { //实例一个Process类,启动一个独立进程 Process p = new Process(); //Process类有一个StartInfo属性 //设定程序名 p.StartInfo.FileName = "cmd.exe"; //设定程式执行参数 “/C”表示执行完命令后马上退出 p.StartInfo.Arguments = string.Format("/c date {0}-{1}-{2}" , year , month , day); //关闭Shell的使用 p.StartInfo.UseShellExecute = false; //重定向标准输入 p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; //重定向错误输出 p.StartInfo.RedirectStandardError = true; //设置不显示doc窗口 p.StartInfo.CreateNoWindow = true; //启动 p.Start(); //从输出流取得命令执行结果 p.StandardOutput.ReadToEnd(); } /// /// 设置本机电脑的时分秒 /// /// /// /// public static void SetLocalTime(int hour , int min , int sec) { //实例一个Process类,启动一个独立进程 Process p = new Process(); //Process类有一个StartInfo属性 //设定程序名 p.StartInfo.FileName = "cmd.exe"; //设定程式执行参数 “/C”表示执行完命令后马上退出 p.StartInfo.Arguments = string.Format("/c time {0}:{1}:{2}" , hour , min , sec); //关闭Shell的使用 p.StartInfo.UseShellExecute = false; //重定向标准输入 p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; //重定向错误输出 p.StartInfo.RedirectStandardError = true; //设置不显示doc窗口 p.StartInfo.CreateNoWindow = true; //启动 p.Start(); //从输出流取得命令执行结果 p.StandardOutput.ReadToEnd(); } /// /// 设置本机电脑的年月日和时分秒 /// /// public static void SetLocalDateTime(DateTime time) { SetLocalDate(time.Year , time.Month , time.Day); SetLocalTime(time.Hour , time.Minute , time.Second); } [StructLayout(LayoutKind.Sequential)] public struct SystemTime { public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMiliseconds; } // 用于设置系统时间 [DllImport("kernel32.dll")] public static extern bool SetLocalTime(ref SystemTime sysTime); // 用于获得系统时间 [DllImport("kernel32.dll")] public static extern void GetLocalTime(ref SystemTime sysTime); public static SystemTime GetSystemTime() { // 创建SystemTime结构体,用于接收系统当前时间 SystemTime systemTime = new SystemTime(); GetLocalTime(ref systemTime); // 获得系统的时间并存在SystemTime结构体中 return systemTime; } public static SystemTime SetSystemTime(DateTime time) { // 创建SystemTime结构体,用于接收用户设置的时间 SystemTime systemTime = new SystemTime(); // 从setDate,setTime控件中获取年,月,日,小时,分钟,秒信息,存入SystemTime结构体中 systemTime.wYear = (ushort)time.Year; systemTime.wMonth = (ushort)time.Month; systemTime.wDay = (ushort)time.Day; systemTime.wHour = (ushort)time.Hour; systemTime.wMinute = (ushort)time.Minute; systemTime.wSecond = (ushort)time.Second; // 将系统的时间设置为用户指定的时间 SetLocalTime(ref systemTime); return systemTime; } /// /// 计算本周的周一日期 /// /// public static DateTime GetMondayDate() { return GetMondayDate(DateTime.Now); } /// /// 计算本周周日的日期 /// /// public static DateTime GetSundayDate() { return GetSundayDate(DateTime.Now); } /// /// 计算某日起始日期(礼拜一的日期) /// /// 该周中任意一天 /// 返回礼拜一日期,后面的具体时、分、秒和传入值相等 public static DateTime GetMondayDate(DateTime someDate) { int i = someDate.DayOfWeek - DayOfWeek.Monday; if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。 TimeSpan ts = new TimeSpan(i , 0 , 0 , 0); return someDate.Subtract(ts); } /// /// 计算某日结束日期(礼拜日的日期) /// /// 该周中任意一天 /// 返回礼拜日日期,后面的具体时、分、秒和传入值相等 public static DateTime GetSundayDate(DateTime someDate) { int i = someDate.DayOfWeek - DayOfWeek.Sunday; if (i != 0) i = 7 - i;// 因为枚举原因,Sunday排在最前,相减间隔要被7减。 TimeSpan ts = new TimeSpan(i , 0 , 0 , 0); return someDate.Add(ts); } /// /// 取得某月的第一天 /// /// 要取得月份第一天的时间 /// public static DateTime FirstDayOfMonth(DateTime datetime) { return datetime.AddDays(1 - datetime.Day); } /// /// 取得某月的最后一天 /// /// 要取得月份最后一天的时间 /// public static DateTime LastDayOfMonth(DateTime datetime) { return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1); } /// /// 取得上个月第一天 /// /// 要取得上个月第一天的当前时间 /// public static DateTime FirstDayOfPreviousMonth(DateTime datetime) { return datetime.AddDays(1 - datetime.Day).AddMonths(-1); } /// /// 取得上个月的最后一天 /// /// 要取得上个月最后一天的当前时间 /// public static DateTime LastDayOfPrdviousMonth(DateTime datetime) { return datetime.AddDays(1 - datetime.Day).AddDays(-1); } /// /// 毫秒时间戳格式化 /// /// /// /// public static string GetFormatDateTime(string timeStamp, string format = null) { if (string.IsNullOrEmpty(timeStamp)) return null; format = format ?? "yyyy-MM-dd HH:mm:ss"; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 DateTime dt = startTime.AddMilliseconds(long.Parse(timeStamp)); return dt.ToString(format); } /// /// 秒时间戳格式化 /// /// /// /// public static string GetFormatDateTime4Sec(string secTimeStamp, string format = null) { if (string.IsNullOrEmpty(secTimeStamp)) return null; format = format ?? "yyyy-MM-dd HH:mm:ss"; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 DateTime dt = startTime.AddSeconds(long.Parse(secTimeStamp)); return dt.ToString(format); } /// /// 获取两个时间相差的分钟数 /// /// /// /// public static double ExecDateDiff(DateTime dateBegin, DateTime dateEnd) { TimeSpan ts1 = new TimeSpan(dateBegin.Ticks); TimeSpan ts2 = new TimeSpan(dateEnd.Ticks); TimeSpan ts3 = ts1.Subtract(ts2).Duration(); //你想转的格式 return System.Math.Abs(ts3.TotalMinutes); } /// /// 获取两个时间相差的分钟数 /// /// /// /// public static string MinuteDiff(DateTime dateBegin , DateTime dateEnd) { TimeSpan ts1 = new TimeSpan(dateBegin.Ticks); TimeSpan ts2 = new TimeSpan(dateEnd.Ticks); TimeSpan ts = ts1.Subtract(ts2).Duration(); return ts.ToString(@"hh\:mm"); } /// /// 获取当前格式化的时间 /// /// public static string GetNowFormat() { return GetNowFormat("yyyy-MM-dd HH:mm:ss"); } public static string GetNowFormat(string format) { format = format ?? "yyyy-MM-dd HH:mm:ss"; return DateTime.Now.ToString(format); } /// /// 营业时间段转换,可以根据类型,返回对应的时间段 /// /// /// /// /// public static Tuple CalculateBusinessPlanDate(ReportQuickDate type, DateTime currStartTime, DateTime currEndTime) { DateTime startTime, endTime; switch (type) { case ReportQuickDate.今天: { startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple); } break; case ReportQuickDate.昨天: { startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).AddDays(-1); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple).AddDays(-1); } break; case ReportQuickDate.前一天: { startTime = currStartTime.AddDays(-1); if (Global.Instance.BusinessPlan.EndType == 0) //当日 { endTime = DateTime.Parse(string.Format("{0} {1}", startTime.ToString("yyyy-MM-dd"), currEndTime.ToString("HH:mm:ss"))); } else //次日 { endTime = DateTime.Parse(string.Format("{0} {1}", startTime.AddDays(1).ToString("yyyy-MM-dd"), currEndTime.ToString("HH:mm:ss"))); } } break; case ReportQuickDate.本周: { var dayOfWeek = (int)DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).DayOfWeek - 1; if (dayOfWeek == -1) { //周日 dayOfWeek = 6; } startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).AddDays(-dayOfWeek); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple); } break; case ReportQuickDate.上周: { var dayOfWeek = (int)DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).DayOfWeek - 1; if (dayOfWeek == -1) { //周日 dayOfWeek = 6; } startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).AddDays(-dayOfWeek - 7); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple).AddDays(-dayOfWeek - 1); } break; case ReportQuickDate.本月: { var day = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).Day - 1; startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).AddDays(-day); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple); } break; case ReportQuickDate.上月: { var day = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).Day - 1; startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple).AddDays(-day).AddMonths(-1); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple).AddDays(-day - 1); } break; default: { startTime = DateTime.Parse(Global.Instance.BusinessPlan.StartTimeSimple); endTime = DateTime.Parse(Global.Instance.BusinessPlan.EndTimeSimple); } break; } return new Tuple(startTime, endTime); } /// /// 通过时间秒毫秒数判断两个时间的间隔 /// /// /// /// public static int DifferentDaysByMillisecond(string date1, string date2) { int sub = 0; try { DateTime dt1 = Convert.ToDateTime(date1); DateTime dt2 = Convert.ToDateTime(date2); sub = (int)((dt1.Ticks/ 10000 - dt2.Ticks/10000) / (1000 * 3600 * 24)); } catch (Exception) { } return sub; } } }