167

I don't want user to give the back date or time.

How can I compare if the entered date and time is LESS then the current time?

If the current date and Time is 17-Jun-2010 , 12:25 PM , I want user cannot give date before 17 Jun -2010 and time before 12:25 PM.

Like my function return false if the time entered by user is 16-Jun-2010 and time 12:24 PM

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
Ashish Ashu
  • 14,169
  • 37
  • 86
  • 117

9 Answers9

335

Microsoft has also implemented the operators '<' and '>'. So you use these to compare two dates.

if (date1 < DateTime.Now)
   Console.WriteLine("Less than the current time!");
MuSTaNG
  • 3,832
  • 2
  • 14
  • 6
  • 7
    Source MSDN; these are documeted as DateTime Operators awkwardly labelled as "DateTime.Greater than", "DateTime.LessThanOrEqualTo"..... https://msdn.microsoft.com/en-us/library/ff986512%28v=vs.90%29.aspx – Salman Siddiqui Jan 23 '15 at 18:09
  • current .NET version: https://msdn.microsoft.com/en-us/library/ff986512(v=vs.110).aspx – juFo Sep 21 '16 at 14:54
  • 3
    I'm using Unity 2017 and using this operator to sort lists gives me wrong results. I even tried to compare DateTime.ticks directly and that failed, too. I had to use DateTime.CompareTo to arrive at right results and I don't know why. – lin Jan 04 '18 at 09:08
  • 3
    This is wrong. This can't compare UTC and Local Time in the right way. – Altiano Gerung May 24 '18 at 13:12
  • 9
    This is not complete answer. When taking DateTime Kind to ocnsideration, it should be either `date1.ToLocalTime() < DateTime.Now` or `date1.ToUniversalTime() < DateTime.UtcNow`. – yurislav Sep 27 '18 at 11:46
206

MSDN: DateTime.Compare

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
Ahmet Kakıcı
  • 6,294
  • 4
  • 37
  • 49
  • 5
    Your answer provides a way to see what the difference is instead of just knowing that the date is before or after. Of course his answer is better for the OP, but yours is better for some people who got here from google (self included). – levininja Apr 14 '17 at 18:46
  • 2
    I found your answer valuable because I'm looking at some legacy code where this is used – Erik Bergstedt Jul 03 '17 at 07:16
  • Here is the [MSDN link](https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx#Examples) – Harsh Raj Jun 29 '18 at 09:40
  • But from debug point of view, MuSTaNG's answer is more readable. – Himalaya Garg Sep 14 '18 at 08:04
  • See my answer, below, for utility code which shows the differences between two dates. It also makes it possible to compare dates only up to a certain point, for example excluding milliseconds or only comparing Y/M/D, or day-hour-minute,... – cskwg Sep 14 '20 at 14:32
28

MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.


The conventional operators

are available for DateTime since .NET Framework 1.1. Also, addition and subtraction of DateTime objects are also possible using conventional operators + and -.

One example from MSDN:

Equality:
System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;

Other operators can be used likewise.

Here is the list all operators available for DateTime.

Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
  • 1
    You could just edit their answer to elaborate. In any case, you cannot use `+` for two `DateTime` operands, You can do `DateTime - DateTime`, or `DateTime + TimeSpan`, or `DateTime - TimeSpan`. – Joey Oct 25 '16 at 07:05
9

If you have two DateTime that looks the same, but Compare or Equals doesn't return what you expect, this is how to compare them.

Here an example with 1-millisecond precision:

bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);
Dharman
  • 30,962
  • 25
  • 85
  • 135
7

In general case you need to compare DateTimes with the same Kind:

if (date1.ToUniversalTime() < date2.ToUniversalTime())
    Console.WriteLine("date1 is earlier than date2");

Explanation from MSDN about DateTime.Compare (This is also relevant for operators like >, <, == and etc.):

To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.

Thus, a simple comparison may give an unexpected result when dealing with DateTimes that are represented in different timezones.

AlbertK
  • 11,841
  • 5
  • 40
  • 36
1
//Time compare.
private int CompareTime(string t1, string t2)
{
    TimeSpan s1 = TimeSpan.Parse(t1);
    TimeSpan s2 = TimeSpan.Parse(t2);
    return s2.CompareTo(s1);
}
0

Here's a typical simple example in the Unity milieu

using UnityEngine;

public class Launch : MonoBehaviour
{
    void Start()
    {
        Debug.Log("today " + System.DateTime.Now.ToString("MM/dd/yyyy"));

        // don't allow the app to be run after June 10th
        System.DateTime lastDay = new System.DateTime(2020, 6, 10);
        System.DateTime today = System.DateTime.Now;

        if (lastDay < today) {
            Debug.Log("quit the app");
            Application.Quit();
        }
        UnityEngine.SceneManagement.SceneManager.LoadScene("Welcome");
    }
}
Fattie
  • 27,874
  • 70
  • 431
  • 719
0
using System;
//
public enum TimeUnit : byte {
    Unknown = 0x00, // 
    Nanosecond = 0x01, // ns, not available in DateTime
    Millisecond = 0x02, // ms
    Second = 0x04, // sec
    Minute = 0x08, // min
    Hour = 0x10, // h
    Day = 0x20, // d
    Month = 0x40, // M
    Year = 0x80, // Y
    AllDate = TimeUnit.Year | TimeUnit.Month | TimeUnit.Day,
    AllTime = TimeUnit.Hour | TimeUnit.Minute | TimeUnit.Second,
    UpToNanosecond = TimeUnit.Nanosecond | TimeUnit.Millisecond | TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToMillisecond = TimeUnit.Millisecond | TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToSecond = TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToMinute = TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToHour = TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToDay = TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToMonth = TimeUnit.Month | TimeUnit.Year,
};
//
public static partial class DateTimeEx {
    //
    private static void _Compare( ref int result, int flags, TimeUnit tu, int a, int b ) {
        var which = (int) tu;
        if ( 0 != ( flags & which ) ) {
            if ( a != b ) result |= which;
        }
    }
    ///<summary>Compare Dates. The returned TimeUnit will have one flag set for every different field. It will NOT indicate which date is bigger or smaller.</summary>
    public static TimeUnit Compare( this DateTime a, DateTime b, TimeUnit unit ) {
        int result = 0;
        var flags = (int) unit;
        //ompare( ref result, flags, TimeUnit.Nanosecond, a.Nano, b.Nanosecond );
        _Compare( ref result, flags, TimeUnit.Millisecond, a.Millisecond, b.Millisecond );
        _Compare( ref result, flags, TimeUnit.Second, a.Second, b.Second );
        _Compare( ref result, flags, TimeUnit.Minute, a.Minute, b.Minute );
        _Compare( ref result, flags, TimeUnit.Hour, a.Hour, b.Hour );
        _Compare( ref result, flags, TimeUnit.Day, a.Day, b.Day );
        _Compare( ref result, flags, TimeUnit.Month, a.Month, b.Month );
        _Compare( ref result, flags, TimeUnit.Year, a.Year, b.Year );
        return (TimeUnit) result;
    }
}
public static class Tests {
    //
    private static void TestCompare() {
        var test = DateTime.UtcNow;
        var ts = test.ToUnixTimestamp( true );
        var test2 = DateTimeEx.ToDateTime( ts, true );
        var ok = 0 == DateTimeEx.Compare( test, test2, TimeUnit.UpToSecond );
        Log.Assert( ok );
        ts = test.ToUnixTimestamp( false );
        test2 = DateTimeEx.ToDateTime( ts, false );
        ok = 0 == DateTimeEx.Compare( test, test2, TimeUnit.UpToSecond );
        Log.Assert( ok );
    }
}
cskwg
  • 790
  • 6
  • 13
-2
public static bool CompareDateTimes(this DateTime firstDate, DateTime secondDate) 
{
   return firstDate.Day == secondDate.Day && firstDate.Month == secondDate.Month && firstDate.Year == secondDate.Year;
}
Jesse
  • 3,522
  • 6
  • 25
  • 40
  • 5
    In .NET, "Compare" usually means "relative comparison" and not "equality check". The question here was about relative comparison. Additionally you made no effort to format the code properly. – Lasse V. Karlsen Jul 31 '18 at 08:30