c# - How to check if a DateTime is between two given dates

DateTime between
datetime-between.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  
    
<!DOCTYPE html>      
<script runat="server">
    public static bool Between(DateTime dateToCheck, DateTime startDate, DateTime endDate)
    {
        return (dateToCheck > startDate && dateToCheck < endDate);
    }    
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a datetime variable with today
        DateTime today = DateTime.Today;

        TimeSpan ts = new TimeSpan(1, 0, 0, 0);
        DateTime yesterday = today.Subtract(ts);
        DateTime nextday = today.AddDays(1);
        DateTime nextWeek = today.AddDays(7);
        
        Label1.Text = "Today : " + today.ToLongDateString();
        Label1.Text += "<br />Yesterday : " + yesterday.ToLongDateString();
        Label1.Text += "<br />Next Day : " + nextday.ToLongDateString();
        Label1.Text += "<br />Next Week : " + nextWeek.ToLongDateString();

        Label1.Text += "<br /><br />";
        Label1.Text += "Is today between yesterday and next day : ";
        Label1.Text += Between(today, yesterday, nextday);

        Label1.Text += "<br /><br />";
        Label1.Text += "Is yesterday between today and next week : ";
        Label1.Text += Between(yesterday, today, nextWeek);
    }
</script>      
      
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - datetime between</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - datetime between
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="Large"    
            Font-Names="Comic Sans MS"
            >      
        </asp:Label>      
        <br /><br />    
        <asp:Button       
            ID="Button1"       
            runat="server"       
            Text="check datetime between two dates"      
            OnClick="Button1_Click"    
            Height="40"      
            Font-Bold="true"      
            />      
    </div>      
    </form>      
</body>      
</html>
More c# examples