dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online Memberspragna
Minu
Matt M
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » Code Snippets » ASP.NET WebForms

Date Comparison in C#


Posted Date:     Category: ASP.NET WebForms    
Author: Member Level: Gold    Points: 15



 


Sometime you may need to compare dates which are stored in variables in string format.

The following CompareDates() function written in C# will help you to accept two dates StartDate and EndDate in string format, convert them into date format, compares them and returns -1 if StartDate less than EndDate, 0 if Equal and 1 if StartDate greater than EndDate.

I assume that the user will enter the date in dd/MM/yyyy format. But if we use Convert.ToDateTime() or DateTime.Parse() methods, these functions will use the applications cultural settings specified in the configuration file or local settings of the computer.

Therefore we need to use cultural info to format the date before the convertion.

I have used English (United Kingdom) cultural inforamtion to convert data into dd/MM/yyyy format using CultureInfo and DateTimeFormatInfo classes. These classes are available in the System.Globalization namespace.



using System;
using System.Globalization;

public class Helper
{
/// Returns -1 if StartDate less than EndDate,
/// 0 if Equal.
/// 1 if StartDate greater than EndDate
public static int CompareDates(string strStartDate, string strEndDate)
{
try
{
// Creates and initializes the CultureInfo which uses the international sort.
//I have used English (United Kingdom) cultural inforamtion to convert data into dd/MM/yyyy format
CultureInfo cultInfo = new CultureInfo("en-GB", true);
DateTimeFormatInfo formatInfo = cultInfo.DateTimeFormat;

formatInfo.ShortDatePattern = "dd/MM/yy";
formatInfo.ShortDatePattern = "dd/MM/yyyy";
formatInfo.LongDatePattern = "dd MMMM yyyy";
formatInfo.FullDateTimePattern = "dd MMMM yyyy HH:mm:ss";

DateTime startDate = new DateTime();
DateTime endDate = new DateTime();

//Convert strStartDate which is passed as string argument into date
if (!String.IsNullOrEmpty(strStartDate))
startDate = System.Convert.ToDateTime(strStartDate, formatInfo);

//Convert strEndDate which is passed as string argument into date
if (!String.IsNullOrEmpty(strEndDate))
endDate = System.Convert.ToDateTime(strEndDate, formatInfo);

return DateTime.Compare(startDate, endDate);


}
catch (Exception ex)
{
throw ex;
}
}
}




To test this function, write the following code in the button _click event of an asp.net button.



protected void Button1_Click(object sender, EventArgs e)
{
string stDate = "20/04/2009";
string enDate = "11/06/2009";
int result = Helper.CompareDates(stDate, enDate);

if (result < 0)
Response.Write(stDate + " is less than " + enDate);
else if (result == 0)
Response.Write(stDate + " is equal to " + enDate);
else
Response.Write(stDate + " is greater than " + enDate);

}






Did you like this resource? Share it with your friends and show your love!


Responses to "Date Comparison in C#"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: Login form in Asp.net
    Previous Resource: Insert values Through Stored Procedure along with the JavaScript Validation
    Return to Resources
    Post New Resource
    Category: ASP.NET WebForms


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    (No tags found.)



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.