Posted By

dmilligan on 08/29/15


Tagged

DateTime truncate extensions


Versions (?)

DateTime Truncate Extension Method


 / Published in: C#
 

Extension method to truncate a DateTime

  1. public static class DateTimeExtensions
  2. {
  3. public static DateTime Truncate(this DateTime self, DateTimeResolution resolution = DateTimeResolution.Second)
  4. {
  5. switch (resolution)
  6. {
  7. case DateTimeResolution.Year:
  8. return new DateTime(self.Year, 1, 1, 0, 0, 0, 0, self.Kind);
  9. case DateTimeResolution.Month:
  10. return new DateTime(self.Year, self.Month, 1, 0, 0, 0, self.Kind);
  11. case DateTimeResolution.Day:
  12. return new DateTime(self.Year, self.Month, self.Day, 0, 0, 0, self.Kind);
  13. case DateTimeResolution.Hour:
  14. return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerHour));
  15. case DateTimeResolution.Minute:
  16. return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerMinute));
  17. case DateTimeResolution.Second:
  18. return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerSecond));
  19. case DateTimeResolution.Millisecond:
  20. return self.AddTicks(-(self.Ticks % TimeSpan.TicksPerMillisecond));
  21. case DateTimeResolution.Tick:
  22. return self.AddTicks(0);
  23. default:
  24. throw new ArgumentException("unrecognized resolution", "resolution");
  25. }
  26. }
  27.  
  28. }

Report this snippet  

You need to login to post a comment.