• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 175
  • Last Modified:

Please help with date algorithm

Given any date, I want to subtract days from that date until the date equals a "Sunday".

If executed on a Sunday, the from and to date range would be from Sunday to Sunday:

Sample method calls:

public class DateRange()
{
   public DateRange(){}

  public DateTime fromDate;
  public DateTime toDate;

  public void CreateRangeGivenDate(DateTime tempdt)
{
???
}

}//end of class


//calling code....


CreateDateRange cdr = new CreateDateRange();
cdr.CreateRangeGivenDate("12/22/2009")

//cdr.FromDate would now equal 12/20/2009
//cdr.ToDate would now equal 12/22/2009


cdr.CreateRangeGivenDate("12/20/2009")

//cdr.FromDate would now equal 12/20/2009
//cdr.ToDate would also equal 12/20/2009


cdr.CreateRangeGivenDate("12/26/2009")

//cdr.FromDate would now equal 12/20/2009
//cdr.ToDate would equal 12/26/2009
0
Tom Knowlton
Asked:
Tom Knowlton
1 Solution
 
rajeeshmcaCommented:
Hi knowlton,
try the below code.. this will work

vb version

Dim dtDate As Date
        Dim sFromdate As String
        Dim sToDate As String
        dtDate = Convert.ToDateTime(DateTextBox.Text)
        sToDate = dtDate.ToShortDateString()
        While dtDate.DayOfWeek <> DayOfWeek.Sunday
            dtDate = dtDate.AddDays(-1)
        End While
        sFromdate = dtDate.ToShortDateString()
        FromDateTextBox.Text = sFromdate

c# version

    System.DateTime dtDate = default(System.DateTime);
    string sFromdate = null;
    string sToDate = null;
    dtDate = Convert.ToDateTime(DateTextBox.Text);
    sToDate = dtDate.ToShortDateString();
    while (dtDate.DayOfWeek != DayOfWeek.Sunday) {
        dtDate = dtDate.AddDays(-1);
    }
    sFromdate = dtDate.ToShortDateString();
    FromDateTextBox.Text = sFromdate;
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now