Home DotNet How to Calculate difference between two dates in C#
How to Calculate difference between two dates in C#

Do you need to find the difference in number of days, hours or even minute between the two date range?

Here's how:

Assuming the a and b variable is of type DateTime object.

DateTime a = DateTime.Now;
DateTime b = DateTime.Now
(b - a).TotalDays

datetimepicker-difference-between-dates

Example:

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            this.dateTimePicker1.CustomFormat = "MM/dd/yyyy HH:mm";

            this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom;

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            //Calculate the total number of days

            textBox1.Text = (dateTimePicker2.Value - dateTimePicker1.Value).TotalDays.ToString("#");

 

            //Calculate the total number of hours

            textBox2.Text = (dateTimePicker2.Value - dateTimePicker1.Value).TotalHours.ToString("#");

 

            //Other options are total of minutes, seconds and milliseconds.

        }

    }

}

 



Comments (2)
  • tselane  - thnx
    just wt i was lukin 4.it wox
  • Anonymous
    :0 :) ;))
Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:D:angry::angry-red::evil::idea::love::x:no-comments::ooo::pirate::?::(
:sleep::););)):0
Security
Please input the anti-spam code that you can read in the image.

"