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
    Hi,

    Below links explain clearly on how to compare 2 times,
    http://stackoverflow.com/questions/10290187/how-to-compare-time-part-of-datetime
    http://forums.asp.net/t/1025431.aspx?How+to+compare+Time+in+C+

    Cheers,
    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");
    }
    else
    {
    MessageBox.Show("dt2 is greater");
    }
    }

    -----------------------------------------------------------------------------
    Regards,
    Gopi A.
    +91 9894315571
    Skype:gopi.net
    http://asaigopi-dotnet.blogspot.in/

  • #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.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com


  • Sign In to post your comments