c# - How to subtract two DateTimes

Subtract two DateTimes
The following asp.net c# example code demonstrate us how can we subtract two DateTime objects programmatically at run time in an asp.net application. .Net framework's DateTime.Subtract() method allow us to subtract the specified time or duration from this instance. DateTime.Subtract() method is overloaded, those are DateTime.Subtract(DateTime) and DateTime.Subtract(TimeSpan).

DateTime.Subtract(DateTime) overloaded method subtract the specified date and time from the instance. We need to pass a DateTime object to this method as parameter. This method return a System.TimeSpan type value. The return TimeSpan object represent a time interval that is equal to date and time of instance minus date and time of parameter.

DateTime.Subtract(TimeSpan) overloaded method subtract the specified duration from this instance. This method required to pass a TimeSpan object as parameter. The TimeSpan represent the time interval to subtract. This overloaded method return a System.DateTime object which is equal to date and time of instance minus time interval of parameter.

After getting the return TimeSpan value from DateTime.Subtract(DateTime) method, we can convert the TimeSpan to total days, hours, minutes, seconds etc. So we can get total days, hours, minutes difference between two date time objects.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime firstDateTime = DateTime.Now;
        DateTime secondDateTime = DateTime.Now.AddDays(3);
        TimeSpan dateTimeDifference;
        dateTimeDifference = secondDateTime.Subtract(firstDateTime);

        double totalHours = dateTimeDifference.TotalHours;

        Label1.Text = "FirstDateTime: " + firstDateTime.ToString();
        Label1.Text += "<br />SecondDateTime: " + secondDateTime.ToString();
        Label1.Text += "<br /><br />Total Hours Difference Between Two DateTime Object: " + totalHours;

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to subtract between two date time object</title>
    <form id="form1" runat="server">
        <h2 style="color:Green">asp.net date time example: subtract date time</h2>
        <br /><br />
             Text="Subtract Two DateTime Object"
More c# examples