Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to find the date difference in C#



A date and time format string defines the text representation of a DateTime value that results from a formatting operation. In C# by calling any of the overloads of the DateTime constructor that allow you to specify specific elements of the date and time value like a year, month or day.

DateTime newDate = new DateTime(2000, 5, 1);

Here newDate represents year as 2000 and month as of May and date as 1.
A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation. The DateTime subtract method may be used in order to find the date-time difference between two instances of the DateTime method.

System.TimeSpan diff = secondDate.Subtract(firstDate);

You can also find the difference between two dates using the following method.

String diff2 = (secondDate - firstDate).TotalDays.ToString();

Convert String to DateTime

You can use the methods like Convert.ToDateTime(String), DateTime.Parse() and DateTime.ParseExact() methods for converting a string-based date to a System.DateTime object. More about….. String to DateTime

DateTimePicker Control

The most important property of the DateTimePicker is the Value property, which holds the selected date and time. More about….. DateTimePicker

using System;
using System.Windows.Forms;

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

		private void button1_Click(object sender, EventArgs e)
		{
			System.DateTime firstDate = new System.DateTime(2000, 01, 01);
			System.DateTime secondDate = new System.DateTime(2000, 05, 31);

			System.TimeSpan diff = secondDate.Subtract(firstDate);
			System.TimeSpan diff1 = secondDate - firstDate;

			String diff2 = (secondDate - firstDate).TotalDays.ToString();

			MessageBox.Show(diff1.ToString ());
		}
	}
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More