How to Calculate difference between two dates in C# z

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.

        }

    }

}

你可能感兴趣的:(Date)