To find out the difference between two days in c#.net is not directly possible. For this We use the Subtract() method of the TimeSpan class.
The following code snippet helps you for calculating the difference between two dates:-
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;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDate_Click(object sender, EventArgs e)
{
string MyString = "Jan 1, 2002, 10:12:50";
DateTime MyDateTime = DateTime.Parse(MyString);
DateTime currentDate = DateTime.Now;//Getting the current system date and time;
TimeSpan span = currentDate.Subtract(MyDateTime);
int days = span.Days;
int hours = span.Hours;
int minute = span.Minutes;
int second = span.Seconds;
int milisecond = span.Milliseconds;
}
}
}
Note:- The TimeSpan class is capable of returning difference interms of Days, Hours, Minutes, Seconds and Milliseconds only. It is not having a property to show difference interms of Months and years.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment