简体   繁体   中英

I need to default dates in two date textboxes to specify date ranges from and to dates

I need to get the last saturday and previous sunday of last saturday based on current date (for eg if todays is 5/21/2014 i need to get 5/17/2014(saturday) and 5/11/2014(sunday) )and if today is saturday then it should be today's date and last sunday (for eg if today is 5/24/2014 i should be getting 5/18/2014)

here's what i am trying to accomplish but its not giving me correct output

            DateTime currentDate = DateTime.Today;
            int offset = currentDate.DayOfWeek - DayOfWeek.Sunday;
            offset = (offset < 0) ? 6 : offset;
            string strCulture =  System.Globalization.CultureInfo.CurrentCulture.Name;

            if (currentDate.DayOfWeek == DayOfWeek.Saturday)
            {
                txtStartDate.Text = strCulture == "en-US" ? currentDate.AddDays(-offset).ToString("MM-dd-yyyy") : currentDate.AddDays(-offset).ToString("dd-MM-yyyy") ;
                txtEndDate.Text = strCulture == "en-US" ? currentDate.ToString("MM-dd-yyyy") : currentDate.ToString("dd-MM-yyyy");
            }
            else
            {
                offset = currentDate.DayOfWeek - DayOfWeek.Saturday;
                offset = (offset < 0) ? 6 : offset;
                DateTime lastSaturday = DateTime.Today.AddDays(-offset);
                offset = lastSaturday.DayOfWeek - DayOfWeek.Sunday;
                offset = (offset < 0) ? 6 : offset;
                DateTime lastSunday = lastSaturday.AddDays(-offset);
                txtStartDate.Text = strCulture == "en-US"? lastSunday.ToString("MM-dd-yyyy"):lastSunday.ToString("dd-MM-yyyy");
                txtEndDate.Text = strCulture == "en-US" ? lastSaturday.ToString("MM-dd-yyyy") : lastSaturday.ToString("dd-MM-yyyy");
            }

You can get the day of the week with DateTime.Now.DayOfWeek. Then get to the previous Sunday by substracting a number of days equal to that day, because Sunday has a value of 0.

int days = (int)DateTime.Now.DayOfWeek;
DateTime lastSunday = DateTime.Now.AddDays(-days);
var today = DateTime.Now.Date;
DateTime lastSaturday, lastSunday;
if(today.DayOfWeek == DayOfWeek.Saturday)
{
    lastSaturday = today;        
}
else
{
    int offset = today.DayOfWeek - DayOfWeek.Monday;

    var moday = today.AddDays(-offset);// Monday of current week
    lastSaturday = monday.AddDays(-2);
}
lastSunday = lastSaturday.AddDays(-6);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM