DateHelper.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Microsoft.CodeAnalysis.CSharp.Syntax;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace Bowin.Common.Utility
  6. {
  7. public static class DateHelper
  8. {
  9. public static DateTime GetYearMonthStartDate(int yearMonth)
  10. {
  11. return DateTime.ParseExact(yearMonth.ToString() + "01", "yyyyMMdd", null);
  12. }
  13. public static string FormatYearMonth(int yearMonth, string formatString)
  14. {
  15. return GetYearMonthStartDate(yearMonth).ToString(formatString);
  16. }
  17. public static bool IsYearMonthBetween(int yearMonth, int fromMonth, int toMonth)
  18. {
  19. var yearMonthDate = GetYearMonthStartDate(yearMonth);
  20. var fromDate = new DateTime(DateTime.Today.Year, fromMonth, 1);
  21. DateTime toDate;
  22. if (toMonth >= fromMonth)
  23. {
  24. toDate = new DateTime(DateTime.Today.Year, toMonth, 1);
  25. }
  26. else
  27. {
  28. toDate = new DateTime(DateTime.Today.Year + 1, toMonth, 1);
  29. }
  30. return yearMonthDate >= fromDate && yearMonthDate <= toDate;
  31. }
  32. public static double GetYearSpan(DateTime fromDate, DateTime toDate)
  33. {
  34. double yearSpanBase = toDate.Year - fromDate.Year;
  35. double toDateYearDays = DateTime.IsLeapYear(toDate.Year) ? 366 : 365;
  36. DateTime toYearBase;
  37. if (fromDate.Month == 2 && fromDate.Day > DateTime.DaysInMonth(toDate.Year, 2))
  38. {
  39. toYearBase = new DateTime(toDate.Year, 2, DateTime.DaysInMonth(toDate.Year, 2));
  40. }
  41. else
  42. {
  43. toYearBase = new DateTime(toDate.Year, fromDate.Month, fromDate.Day);
  44. }
  45. return yearSpanBase + (toDate.Subtract(toYearBase).TotalDays / toDateYearDays);
  46. }
  47. public static int YearMonthAdd(int yearMonth, int addMonths)
  48. {
  49. return GetYearMonthStartDate(yearMonth).AddMonths(addMonths).ToYearMonth();
  50. }
  51. public static int? YearMonthAdd(int? yearMonth, int addMonths)
  52. {
  53. if (yearMonth.HasValue)
  54. {
  55. return YearMonthAdd(yearMonth.Value, addMonths);
  56. }
  57. else
  58. {
  59. return null;
  60. }
  61. }
  62. public static int ToYearMonth(this DateTime dateTime)
  63. {
  64. return dateTime.Year * 100 + dateTime.Month;
  65. }
  66. /// <summary>
  67. /// 计算两个时间相差的月数
  68. /// </summary>
  69. /// <param name="statrDate"></param>
  70. /// <param name="endDate"></param>
  71. /// <returns></returns>
  72. public static int DiffMonth(DateTime statrDate, DateTime endDate)
  73. {
  74. return (endDate.Year * 12 + endDate.Month - statrDate.Year * 12 - statrDate.Month);
  75. }
  76. }
  77. }