How to compare DateTime current moment with the previously known DateTime to the minute?
2 answers
On the English version of this site there is a solution in the form of cutting off significant units in DateTime. In my opinion, quite a normal solution with the possibility of further expansion.
public static DateTime TruncateTo(this DateTime dt, DateTruncate TruncateTo) { if (TruncateTo == DateTruncate.Year) return new DateTime(dt.Year, 0, 0); else if (TruncateTo == DateTruncate.Month) return new DateTime(dt.Year, dt.Month, 0); else if (TruncateTo == DateTruncate.Day) return new DateTime(dt.Year, dt.Month, dt.Day); else if (TruncateTo == DateTruncate.Hour) return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0); else if (TruncateTo == DateTruncate.Minute) return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0); else return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second); } public enum DateTruncate { Year, Month, Day, Hour, Minute, Second } - 2You lose
DateTime.Kind. - VladD
|
Example:
using System; static class Ex { static public int CompareWithoutSeconds(this DateTime d1, DateTime d2) { if (d1.Minute == d2.Minute && d1.Hour == d2.Hour && d1.Date == d2.Date) { return 0; } return d1.CompareTo(d2); } } class Program { static void Main(string[] args) { DateTime d1 = new DateTime(2009, 12, 11, 13, 35, 48, 95); DateTime d2 = new DateTime(2009, 12, 11, 13, 35, 44, 67); int c = d1.CompareWithoutSeconds(d2); Console.WriteLine(c); } } UPD Here's another cool option:
var d1 = DateTime.Now; var d2 = new DateTime(2016, 04, 11, 15, 14, 01, 0); bool equal = d1.ToString("g") == d2.ToString("g"); - onein UPD really cool option) - DisguisePerceptron
- 3@DisguisePerceptron: Not too cool. The extra string allocation + relies on the current locale. - VladD
|