DateTimeHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. using System;
  2. using System.Diagnostics;
  3. using System.Globalization;
  4. using System.Runtime.InteropServices;
  5. namespace Masuit.Tools.DateTimeExt
  6. {
  7. /// <summary>
  8. /// 日期操作工具类
  9. /// </summary>
  10. public static class DateUtil
  11. {
  12. /// <summary>
  13. /// 获取某一年有多少周
  14. /// </summary>
  15. /// <param name="_"></param>
  16. /// <param name="year">年份</param>
  17. /// <returns>该年周数</returns>
  18. public static int GetWeekAmount(this DateTime _, int year)
  19. {
  20. var end = new DateTime(year, 12, 31); //该年最后一天
  21. var gc = new GregorianCalendar();
  22. return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday); //该年星期数
  23. }
  24. /// <summary>
  25. /// 返回年度第几个星期 默认星期日是第一天
  26. /// </summary>
  27. /// <param name="date">时间</param>
  28. /// <returns>第几周</returns>
  29. public static int WeekOfYear(this in DateTime date)
  30. {
  31. var gc = new GregorianCalendar();
  32. return gc.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
  33. }
  34. /// <summary>
  35. /// 返回年度第几个星期
  36. /// </summary>
  37. /// <param name="date">时间</param>
  38. /// <param name="week">一周的开始日期</param>
  39. /// <returns>第几周</returns>
  40. public static int WeekOfYear(this in DateTime date, DayOfWeek week)
  41. {
  42. var gc = new GregorianCalendar();
  43. return gc.GetWeekOfYear(date, CalendarWeekRule.FirstDay, week);
  44. }
  45. /// <summary>
  46. /// 得到一年中的某周的起始日和截止日
  47. /// 年 nYear
  48. /// 周数 nNumWeek
  49. /// 周始 out dtWeekStart
  50. /// 周终 out dtWeekeEnd
  51. /// </summary>
  52. /// <param name="_"></param>
  53. /// <param name="nYear">年份</param>
  54. /// <param name="nNumWeek">第几周</param>
  55. /// <param name="dtWeekStart">开始日期</param>
  56. /// <param name="dtWeekeEnd">结束日期</param>
  57. public static void GetWeekTime(this DateTime _, int nYear, int nNumWeek, out DateTime dtWeekStart, out DateTime dtWeekeEnd)
  58. {
  59. var dt = new DateTime(nYear, 1, 1);
  60. dt += new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
  61. dtWeekStart = dt.AddDays(-(int)dt.DayOfWeek + (int)DayOfWeek.Monday);
  62. dtWeekeEnd = dt.AddDays((int)DayOfWeek.Saturday - (int)dt.DayOfWeek + 1);
  63. }
  64. /// <summary>
  65. /// 得到一年中的某周的起始日和截止日 周一到周五 工作日
  66. /// </summary>
  67. /// <param name="_"></param>
  68. /// <param name="nYear">年份</param>
  69. /// <param name="nNumWeek">第几周</param>
  70. /// <param name="dtWeekStart">开始日期</param>
  71. /// <param name="dtWeekeEnd">结束日期</param>
  72. public static void GetWeekWorkTime(this DateTime _, int nYear, int nNumWeek, out DateTime dtWeekStart, out DateTime dtWeekeEnd)
  73. {
  74. var dt = new DateTime(nYear, 1, 1);
  75. dt += new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
  76. dtWeekStart = dt.AddDays(-(int)dt.DayOfWeek + (int)DayOfWeek.Monday);
  77. dtWeekeEnd = dt.AddDays((int)DayOfWeek.Saturday - (int)dt.DayOfWeek + 1).AddDays(-2);
  78. }
  79. #region P/Invoke 设置本地时间
  80. [DllImport("kernel32.dll")]
  81. private static extern bool SetLocalTime(ref SystemTime time);
  82. [StructLayout(LayoutKind.Sequential)]
  83. private struct SystemTime
  84. {
  85. public short year;
  86. public short month;
  87. public short dayOfWeek;
  88. public short day;
  89. public short hour;
  90. public short minute;
  91. public short second;
  92. public short milliseconds;
  93. }
  94. /// <summary>
  95. /// 设置本地计算机系统时间,仅支持Windows系统
  96. /// </summary>
  97. /// <param name="dt">DateTime对象</param>
  98. public static void SetLocalTime(this in DateTime dt)
  99. {
  100. SystemTime st;
  101. st.year = (short)dt.Year;
  102. st.month = (short)dt.Month;
  103. st.dayOfWeek = (short)dt.DayOfWeek;
  104. st.day = (short)dt.Day;
  105. st.hour = (short)dt.Hour;
  106. st.minute = (short)dt.Minute;
  107. st.second = (short)dt.Second;
  108. st.milliseconds = (short)dt.Millisecond;
  109. SetLocalTime(ref st);
  110. }
  111. #endregion
  112. /// <summary>
  113. /// 返回相对于当前时间的相对天数
  114. /// </summary>
  115. /// <param name="dt"></param>
  116. /// <param name="relativeday">相对天数</param>
  117. public static string GetDateTime(this in DateTime dt, int relativeday)
  118. {
  119. return dt.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
  120. }
  121. /// <summary>
  122. /// 返回标准时间格式string
  123. /// </summary>
  124. public static string GetDateTimeF(this in DateTime dt) => dt.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
  125. /// <summary>
  126. /// 获取该时间相对于1970-01-01T00:00:00Z的秒数
  127. /// </summary>
  128. /// <param name="dt"></param>
  129. /// <returns></returns>
  130. public static double GetTotalSeconds(this in DateTime dt) => new DateTimeOffset(dt).ToUnixTimeSeconds();
  131. /// <summary>
  132. /// 获取该时间相对于1970-01-01T00:00:00Z的毫秒数
  133. /// </summary>
  134. /// <param name="dt"></param>
  135. /// <returns></returns>
  136. public static double GetTotalMilliseconds(this in DateTime dt) => new DateTimeOffset(dt).ToUnixTimeMilliseconds();
  137. /// <summary>
  138. /// 获取该时间相对于1970-01-01T00:00:00Z的微秒时间戳
  139. /// </summary>
  140. /// <param name="dt"></param>
  141. /// <returns></returns>
  142. public static long GetTotalMicroseconds(this in DateTime dt) => (new DateTimeOffset(dt).UtcTicks - 621355968000000000) / 10;
  143. [DllImport("Kernel32.dll")]
  144. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  145. /// <summary>
  146. /// 获取该时间相对于1970-01-01T00:00:00Z的纳秒时间戳
  147. /// </summary>
  148. /// <param name="dt"></param>
  149. /// <returns></returns>
  150. public static long GetTotalNanoseconds(this in DateTime dt)
  151. {
  152. var ticks = (new DateTimeOffset(dt).UtcTicks - 621355968000000000) * 100;
  153. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  154. {
  155. QueryPerformanceCounter(out var timestamp);
  156. return ticks + timestamp % 100;
  157. }
  158. return ticks + Stopwatch.GetTimestamp() % 100;
  159. }
  160. /// <summary>
  161. /// 获取该时间相对于1970-01-01T00:00:00Z的分钟数
  162. /// </summary>
  163. /// <param name="dt"></param>
  164. /// <returns></returns>
  165. public static double GetTotalMinutes(this in DateTime dt) => new DateTimeOffset(dt).Offset.TotalMinutes;
  166. /// <summary>
  167. /// 获取该时间相对于1970-01-01T00:00:00Z的小时数
  168. /// </summary>
  169. /// <param name="dt"></param>
  170. /// <returns></returns>
  171. public static double GetTotalHours(this in DateTime dt) => new DateTimeOffset(dt).Offset.TotalHours;
  172. /// <summary>
  173. /// 获取该时间相对于1970-01-01T00:00:00Z的天数
  174. /// </summary>
  175. /// <param name="dt"></param>
  176. /// <returns></returns>
  177. public static double GetTotalDays(this in DateTime dt) => new DateTimeOffset(dt).Offset.TotalDays;
  178. /// <summary>
  179. /// 返回本年有多少天
  180. /// </summary>
  181. /// <param name="_"></param>
  182. /// <param name="iYear">年份</param>
  183. /// <returns>本年的天数</returns>
  184. public static int GetDaysOfYear(this DateTime _, int iYear)
  185. {
  186. return IsRuYear(iYear) ? 366 : 365;
  187. }
  188. /// <summary>本年有多少天</summary>
  189. /// <param name="dt">日期</param>
  190. /// <returns>本天在当年的天数</returns>
  191. public static int GetDaysOfYear(this in DateTime dt)
  192. {
  193. //取得传入参数的年份部分,用来判断是否是闰年
  194. int n = dt.Year;
  195. return IsRuYear(n) ? 366 : 365;
  196. }
  197. /// <summary>本月有多少天</summary>
  198. /// <param name="_"></param>
  199. /// <param name="iYear">年</param>
  200. /// <param name="month">月</param>
  201. /// <returns>天数</returns>
  202. public static int GetDaysOfMonth(this DateTime _, int iYear, int month)
  203. {
  204. return month switch
  205. {
  206. 1 => 31,
  207. 2 => (IsRuYear(iYear) ? 29 : 28),
  208. 3 => 31,
  209. 4 => 30,
  210. 5 => 31,
  211. 6 => 30,
  212. 7 => 31,
  213. 8 => 31,
  214. 9 => 30,
  215. 10 => 31,
  216. 11 => 30,
  217. 12 => 31,
  218. _ => 0
  219. };
  220. }
  221. /// <summary>本月有多少天</summary>
  222. /// <param name="dt">日期</param>
  223. /// <returns>天数</returns>
  224. public static int GetDaysOfMonth(this in DateTime dt)
  225. {
  226. //--利用年月信息,得到当前月的天数信息。
  227. return dt.Month switch
  228. {
  229. 1 => 31,
  230. 2 => (IsRuYear(dt.Year) ? 29 : 28),
  231. 3 => 31,
  232. 4 => 30,
  233. 5 => 31,
  234. 6 => 30,
  235. 7 => 31,
  236. 8 => 31,
  237. 9 => 30,
  238. 10 => 31,
  239. 11 => 30,
  240. 12 => 31,
  241. _ => 0
  242. };
  243. }
  244. /// <summary>返回当前日期的星期名称</summary>
  245. /// <param name="idt">日期</param>
  246. /// <returns>星期名称</returns>
  247. public static string GetWeekNameOfDay(this in DateTime idt)
  248. {
  249. return idt.DayOfWeek switch
  250. {
  251. DayOfWeek.Monday => "星期一",
  252. DayOfWeek.Tuesday => "星期二",
  253. DayOfWeek.Wednesday => "星期三",
  254. DayOfWeek.Thursday => "星期四",
  255. DayOfWeek.Friday => "星期五",
  256. DayOfWeek.Saturday => "星期六",
  257. DayOfWeek.Sunday => "星期日",
  258. _ => ""
  259. };
  260. }
  261. /// <summary>判断当前年份是否是闰年,私有函数</summary>
  262. /// <param name="iYear">年份</param>
  263. /// <returns>是闰年:True ,不是闰年:False</returns>
  264. private static bool IsRuYear(int iYear)
  265. {
  266. //形式参数为年份
  267. //例如:2003
  268. var n = iYear;
  269. return n % 400 == 0 || n % 4 == 0 && n % 100 != 0;
  270. }
  271. /// <summary>
  272. /// 判断是否为合法日期,必须大于1800年1月1日
  273. /// </summary>
  274. /// <param name="strDate">输入日期字符串</param>
  275. /// <returns>True/False</returns>
  276. public static bool IsDateTime(this string strDate)
  277. {
  278. DateTime.TryParse(strDate, out var result);
  279. return result.CompareTo(DateTime.Parse("1800-1-1")) > 0;
  280. }
  281. /// <summary>
  282. /// 判断时间是否在区间内
  283. /// </summary>
  284. /// <param name="this"></param>
  285. /// <param name="start">开始</param>
  286. /// <param name="end">结束</param>
  287. /// <param name="mode">模式</param>
  288. /// <returns></returns>
  289. public static bool In(this in DateTime @this, DateTime start, DateTime end, RangeMode mode = RangeMode.Close)
  290. {
  291. return mode switch
  292. {
  293. RangeMode.Open => start < @this && end > @this,
  294. RangeMode.Close => start <= @this && end >= @this,
  295. RangeMode.OpenClose => start < @this && end >= @this,
  296. RangeMode.CloseOpen => start <= @this && end > @this,
  297. _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, null)
  298. };
  299. }
  300. /// <summary>
  301. /// 返回每月的第一天和最后一天
  302. /// </summary>
  303. /// <param name="_"></param>
  304. /// <param name="month">月份</param>
  305. /// <param name="firstDay">第一天</param>
  306. /// <param name="lastDay">最后一天</param>
  307. public static void ReturnDateFormat(this DateTime _, int month, out string firstDay, out string lastDay)
  308. {
  309. int year = DateTime.Now.Year + month / 12;
  310. if (month != 12)
  311. {
  312. month %= 12;
  313. }
  314. switch (month)
  315. {
  316. case 1:
  317. firstDay = DateTime.Now.ToString($"{year}-0{month}-01");
  318. lastDay = DateTime.Now.ToString($"{year}-0{month}-31");
  319. break;
  320. case 2:
  321. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  322. lastDay = DateTime.IsLeapYear(DateTime.Now.Year) ? DateTime.Now.ToString(year + "-0" + month + "-29") : DateTime.Now.ToString(year + "-0" + month + "-28");
  323. break;
  324. case 3:
  325. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  326. lastDay = DateTime.Now.ToString("yyyy-0" + month + "-31");
  327. break;
  328. case 4:
  329. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  330. lastDay = DateTime.Now.ToString(year + "-0" + month + "-30");
  331. break;
  332. case 5:
  333. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  334. lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
  335. break;
  336. case 6:
  337. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  338. lastDay = DateTime.Now.ToString(year + "-0" + month + "-30");
  339. break;
  340. case 7:
  341. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  342. lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
  343. break;
  344. case 8:
  345. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  346. lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
  347. break;
  348. case 9:
  349. firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
  350. lastDay = DateTime.Now.ToString(year + "-0" + month + "-30");
  351. break;
  352. case 10:
  353. firstDay = DateTime.Now.ToString(year + "-" + month + "-01");
  354. lastDay = DateTime.Now.ToString(year + "-" + month + "-31");
  355. break;
  356. case 11:
  357. firstDay = DateTime.Now.ToString(year + "-" + month + "-01");
  358. lastDay = DateTime.Now.ToString(year + "-" + month + "-30");
  359. break;
  360. default:
  361. firstDay = DateTime.Now.ToString(year + "-" + month + "-01");
  362. lastDay = DateTime.Now.ToString(year + "-" + month + "-31");
  363. break;
  364. }
  365. }
  366. /// <summary>
  367. /// 返回某年某月最后一天
  368. /// </summary>
  369. /// <param name="_"></param>
  370. /// <param name="year">年份</param>
  371. /// <param name="month">月份</param>
  372. /// <returns>日</returns>
  373. public static int GetMonthLastDate(this DateTime _, int year, int month)
  374. {
  375. DateTime lastDay = new DateTime(year, month, new GregorianCalendar().GetDaysInMonth(year, month));
  376. int day = lastDay.Day;
  377. return day;
  378. }
  379. /// <summary>
  380. /// 获得一段时间内有多少小时
  381. /// </summary>
  382. /// <param name="dtStar">起始时间</param>
  383. /// <param name="dtEnd">终止时间</param>
  384. /// <returns>小时差</returns>
  385. public static string GetTimeDelay(this in DateTime dtStar, DateTime dtEnd)
  386. {
  387. long lTicks = (dtEnd.Ticks - dtStar.Ticks) / 10000000;
  388. string sTemp = (lTicks / 3600).ToString().PadLeft(2, '0') + ":";
  389. sTemp += (lTicks % 3600 / 60).ToString().PadLeft(2, '0') + ":";
  390. sTemp += (lTicks % 3600 % 60).ToString().PadLeft(2, '0');
  391. return sTemp;
  392. }
  393. /// <summary>
  394. /// 获得8位时间整型数字
  395. /// </summary>
  396. /// <param name="dt">当前的日期时间对象</param>
  397. /// <returns>8位时间整型数字</returns>
  398. public static string GetDateString(this in DateTime dt)
  399. {
  400. return dt.Year + dt.Month.ToString().PadLeft(2, '0') + dt.Day.ToString().PadLeft(2, '0');
  401. }
  402. /// <summary>
  403. /// 返回时间差
  404. /// </summary>
  405. /// <param name="dateTime1">时间1</param>
  406. /// <param name="dateTime2">时间2</param>
  407. /// <returns>时间差</returns>
  408. public static string DateDiff(this in DateTime dateTime1, in DateTime dateTime2)
  409. {
  410. string dateDiff;
  411. var ts = dateTime2 - dateTime1;
  412. if (ts.Days >= 1)
  413. {
  414. dateDiff = dateTime1.Month + "月" + dateTime1.Day + "日";
  415. }
  416. else
  417. {
  418. dateDiff = ts.Hours > 1 ? ts.Hours + "小时前" : ts.Minutes + "分钟前";
  419. }
  420. return dateDiff;
  421. }
  422. /// <summary>
  423. /// 计算2个时间差
  424. /// </summary>
  425. /// <param name="beginTime">开始时间</param>
  426. /// <param name="endTime">结束时间</param>
  427. /// <returns>时间差</returns>
  428. public static string GetDiffTime(this in DateTime beginTime, in DateTime endTime)
  429. {
  430. string strResout = string.Empty;
  431. //获得2时间的时间间隔秒计算
  432. TimeSpan span = endTime.Subtract(beginTime);
  433. int sec = Convert.ToInt32(span.TotalSeconds);
  434. int minutes = 1 * 60;
  435. int hours = minutes * 60;
  436. int day = hours * 24;
  437. int month = day * 30;
  438. int year = month * 12;
  439. //提醒时间,到了返回1,否则返回0
  440. if (sec > year)
  441. {
  442. strResout += sec / year + "年";
  443. sec %= year; //剩余
  444. }
  445. if (sec > month)
  446. {
  447. strResout += sec / month + "月";
  448. sec %= month;
  449. }
  450. if (sec > day)
  451. {
  452. strResout += sec / day + "天";
  453. sec %= day;
  454. }
  455. if (sec > hours)
  456. {
  457. strResout += sec / hours + "小时";
  458. sec %= hours;
  459. }
  460. if (sec > minutes)
  461. {
  462. strResout += sec / minutes + "分";
  463. sec %= minutes;
  464. }
  465. strResout += sec + "秒";
  466. return strResout;
  467. }
  468. }
  469. /// <summary>
  470. /// 区间模式
  471. /// </summary>
  472. public enum RangeMode
  473. {
  474. /// <summary>
  475. /// 开区间
  476. /// </summary>
  477. Open,
  478. /// <summary>
  479. /// 闭区间
  480. /// </summary>
  481. Close,
  482. /// <summary>
  483. /// 左开右闭区间
  484. /// </summary>
  485. OpenClose,
  486. /// <summary>
  487. /// 左闭右开区间
  488. /// </summary>
  489. CloseOpen
  490. }
  491. }