Search

Tuesday, February 25, 2014
2 comments

Calculate duration between two dates in c# programming

5:31 AMTuesday, February 25, 2014

Introduction

Design simple age calculator , calculate remaining days from two dates. Suppose your Date of Birth is 19/mar/1987 and you want to calculate total days on till date. Here we take an simple demonstration of this type of application.

Design

Step-1 : Add two DateTimerPicker and one button control on windows form.
Step-2 : Take Two Datetime class instance, first for starting date and second for ending date.
Step-3 :  Calulate difference between two dates using Timespan structure.
Step-4 :  Using TotalDays property of TimeSpan structure you can calculate days.

Calculate duration between two dates in c# programming

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace datecalulator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime dtstart = dateTimePicker1.Value;
            DateTime enddate = dateTimePicker2.Value;
            TimeSpan totaldays = enddate - dtstart;
            int calculate =Convert .ToInt32 (totaldays.TotalDays);
            MessageBox.Show(calculate.ToString()+" Days");

        }
    }
}

 Code generate the following output

Calculate duration between two dates in c# programming

Protected by Copyscape Online Copyright Protection Software

2 comments :

  1. How to get Years? months? Days?
    like: 24 years 7 months 3 days...

    ReplyDelete
    Replies
    1. using TimeSpan Structure properties like totalDays, totalMoth, totalyears

      Delete

 
Toggle Footer
Top