DateTimeExtension.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Globalization;
  7. namespace EasyDevCore.Common
  8. {
  9. /// <summary>
  10. /// DateTime extension helper
  11. /// </summary>
  12. public static class DateTimeExtensions
  13. {
  14. /// <summary>
  15. /// Parses by format.
  16. /// </summary>
  17. /// <param name="input">The input.</param>
  18. /// <param name="format">The format.</param>
  19. /// <returns></returns>
  20. public static DateTime ParseByFormat(this DateTime input, string format)
  21. {
  22. return DateTime.ParseExact(input.ToString(format), format, System.Globalization.CultureInfo.InvariantCulture);
  23. }
  24. /// <summary>
  25. /// Determines whether this instance is expired.
  26. /// </summary>
  27. /// <param name="input">The input.</param>
  28. /// <returns>
  29. /// <c>true</c> if the specified input is expired; otherwise, <c>false</c>.
  30. /// </returns>
  31. public static bool IsExpired(this DateTime? input)
  32. {
  33. return input != null && input.Value > DateTime.Now;
  34. }
  35. /// <summary>
  36. /// Determines whether this instance is expired.
  37. /// </summary>
  38. /// <param name="input">The input.</param>
  39. /// <returns>
  40. /// <c>true</c> if the specified input is expired; otherwise, <c>false</c>.
  41. /// </returns>
  42. public static bool IsExpired(this DateTime input)
  43. {
  44. return input > DateTime.Now;
  45. }
  46. /// <summary>
  47. /// Gets the week of month.
  48. /// </summary>
  49. /// <param name="time">The time.</param>
  50. /// <returns></returns>
  51. public static int GetWeekOfMonth(this DateTime time)
  52. {
  53. DateTime first = new DateTime(time.Year, time.Month, 1);
  54. return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
  55. }
  56. /// <summary>
  57. /// Gets the week of year.
  58. /// </summary>
  59. /// <param name="time">The time.</param>
  60. /// <returns></returns>
  61. public static int GetWeekOfYear(this DateTime time)
  62. {
  63. return new GregorianCalendar().GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
  64. }
  65. }
  66. }