You must Sign In to post a response.
  • Category: ASP.NET

    How to comapare two hours in C#

    Are you looking for a way to comapare two hours in C# ? then read this thread to know more about it

    how can i compare two hours in c#. i want to know which one is greater.
  • #744435

    Below links explain clearly on how to compare 2 times,

    Vignesh Kannan

  • #744453
    Hi Gandhi,

    Use the below code for comparing hours in c#

    private void button1_Click(object sender, EventArgs e)
    DateTime dt1 = Convert.ToDateTime("02:00:00");
    DateTime dt2 = Convert.ToDateTime("01:00:00");

    if (dt1.TimeOfDay.Hours > dt2.TimeOfDay.Hours)
    MessageBox.Show("dt1 is greater");
    MessageBox.Show("dt2 is greater");

    Gopi A.
    +91 9894315571

  • #744469
    Hai Aman,
    If you want to compare two dates then the format of the date should be same and then only you will get the correct output else you will not get the correct result.
    Lets say if you want to compare two hours then the below conditions can be applicable:

    int hour1 = Convert.ToDataTime("yourFirstvalue").TimeOfDay.Hour;
    int hour2 = Convert.ToDataTime("yourSecondvalue").TimeOfDay.Hour;
    if(hour1 >hour2)
    MessageBox.Show("Hour 1 is greater than hour 2");
    if(hour1 <hour2)
    MessageBox.Show("Hour 1 is less than hour 2");

    Hope it will be helpful to you.

    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)

  • Sign In to post your comments