[c#] How to compare DateTime in C#?

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

This question is related to c# .net datetime

The answer is


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");
    }
}

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!");

//Time compare.
private int CompareTime(string t1, string t2)
{
    TimeSpan s1 = TimeSpan.Parse(t1);
    TimeSpan s2 = TimeSpan.Parse(t2);
    return s2.CompareTo(s1);
}

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 );
    }
}

public static bool CompareDateTimes(this DateTime firstDate, DateTime secondDate) 
{
   return firstDate.Day == secondDate.Day && firstDate.Month == secondDate.Month && firstDate.Year == secondDate.Year;
}

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);

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.


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?