
C# compare dates with CompareTo, Equals and Subtract(only compare dates in days and time)
Date comparison is often used in the development process. For example, sometimes it is necessary to determine whether it is the same day or whether the product has expired, etc. They need to be determined by date comparison. There are usually three methods for C# date comparison.
I. Three methods of C# compare dates
1. C# compare dates with CompareTo() method
Code show as below:
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(-1);
int n = dt1.CompareTo(dt2);
If n > 0, then dt1 > dt2; if n = 0, then dt1 = dt2; if n < 0, then dt1 < dt2.
2. C# compare dates with DateTime.Equals() method
Code show as below:
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(-1);
bool r = DateTime.Equals(dt1, dt2);
If r is true, then dt1 = dt2; if r is false, then dt1 is not equal to dt2.
If you need to determine whether two dates are the same day, this method is convenient and very simple. The code is as follows:
bool oneDay = DateTime.Equals(dt1.Date, dt2.Date);
If oneDay is true, dt1 and dt2 are the same day; if oneDay is false, dt1 and dt2 are not the same day.
3. C# compare dates with Subtract() method(C# compare dates in days)
Code show as below:
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(-1);
TimeSpan ts1 = new TimeSpan(dt1.Ticks);
TimeSpan ts2 = new TimeSpan(dt2.Ticks);
TimeSpan ts = ts1.Subtract(ts2);
int day = ts.Days;
If day > 0, then dt1 > dt2; if day = 0, then dt1 = dt2; if day < 0, then dt1 <dt2. It should be noted that Duration() cannot be added after ts1.Subtract(ts2), because Duration() returns an absolute value, and if you add it, you can't compare it.
II. The application of C# date comparison
1. C# compare dates without time
Code show as below:
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(-1);
int d = dt1.Date.CompareTo(dt2.Date);
If d > 0, then dt1 > dt2; if d = 0, then dt1 = dt2; if d < 0, then dt1 <dt2.
2. C# compare time
Code show as below:
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddMinutes(-3);
int t = dt1.TimeOfDay.CompareTo(dt2.TimeOfDay);
If t > 0, then dt1 > dt2; if t = 0, then dt1 = dt2; if t < 0, then dt1 <dt2.
-
Related Reading
- C# listview select row(a row and multiple rows)
- Solve the flickering problem of C# listview multithr
- C# convert punctuation marks to Unicode encoding
- C# Read and write to text file Newline, with one lin
- C# merge binary array(byte array)
- C# hashtable synchronized and SyncRoot(cost comparis
- C# gridview checkbox cannot get value(reason and sol
- C# Winform button transparent background with proper
- Error cs1010 newline in constant - .net(C#) mislabel
- Convert Unicode to string C#(with string to unicode)
- C# Why does the generated random number repeat and g
- C# start exe with parameters(2 methods) and close ex