Comparing and Adding Dates

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

<script runat="server">
public void Page_Load(Object sender, EventArgs e){

//create the new dates: one by using the property Now
//and another using the DateTime constructor of Year,Month,Day

System.DateTime date1 = System.DateTime.Now;
System.DateTime date2 = new System.DateTime(1972,8,21);

//Show the dates
Response.Write("<hr>");
Response.Write("Show current dates");
Response.Write("<hr>");
Response.Write("date1: " + date1 + "<br>");
Response.Write("date2: " + date2 + "<P>");
Response.Write("Show Date Difference: ");

//Compare the dates
if (DateTime.Compare(date1, date2) > 0) Response.Write("date1 > date2");
if (DateTime.Compare(date1, date2) == 0) Response.Write("date1 == date2");
if (DateTime.Compare(date1, date2) < 0) Response.Write("date1 < date2");

//Add to the second date using AddYears to add 40 years to the date
System.DateTime date2new = date2.AddYears(40);

//Show the dates again this time with the new date2
Response.Write("<p>");
Response.Write("<hr>");
Response.Write("Show new dates with new date 2");
Response.Write("<hr>");
Response.Write("date1: " + date1 + "<br>");
Response.Write("date2new: " + date2new + "<P>");
Response.Write("Show new Date Difference: ");

//Now compare the dates
if (DateTime.Compare(date1, date2new) > 0) Response.Write("date1 > date2new");
if (DateTime.Compare(date1, date2new) == 0) Response.Write("date1 == date2new");
if (DateTime.Compare(date1, date2new) < 0) Response.Write("date1 < date2new");

}
</script>


Attachments

  • Comparing and Adding Dates (15144-3083-Page Language.doc)
  • Comments

    Author: komaladevi30 Apr 2008 Member Level: Gold   Points : 0

    Author: k prabhakar varma05 May 2008 Member Level: Gold   Points : 2

    it is fine for comparing two dates whether greater,lesser and equal.
    But What about Actual scenario Date Difference,i.e. the difference in years,or months, or weeks,or days should be caleculated and be displayed between two Dates.

    Author: shaik mohiuddin07 May 2008 Member Level: Gold   Points : 2

    gud one for intermediate level

    Guest Author: kaarthik29 Sep 2012

    How to add two dates for example

    date1=04/01/2012
    date2=11/17/2012

    if i add date1 and date2 the expected result should be 02/18/2025

    How to do it in csharp.

    Guest Author: kaarthik29 Sep 2012

    How to add two dates for example

    date1=04/01/2012
    date2=11/17/2012

    if i add date1 and date2 the expected result should be 02/18/2025

    How to do it in c-sharp.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: