Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get all dates in the last X months

I want to get all dates in the last three months, so I did the following:

protected void BindPermissions(int empNum)
        {
            var permPeriod = new Dictionary<int, int>();
            permPeriod.Add(DateTime.Now.Year, DateTime.Now.Month);
            permPeriod.Add(DateTime.Now.AddMonths(-1).Year, (DateTime.Now.AddMonths(-1).Month));
            permPeriod.Add(DateTime.Now.AddMonths(-2).Year, (DateTime.Now.AddMonths(-2).Month));
            var dt = payload_object.AttendancePermissionBO.permissionList
                .Where(x => x.empNum == empNum
                && ((x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(0) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(0)) ||
                (x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(1) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(1)) ||
                (x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(2) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(2)))).ToList().OrderBy(x => x.permDate);
            GV_PermissionHistory.DataSource = dt;
            GV_PermissionHistory.DataBind();
        }

Is there a better way to do that or this method suits what i need?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. Get the date (boundary) three months ago from today.
DateTime threeMonthsAgoDate = DateTime.Now.AddMonths(-3);
  1. Filter the data for permDate that after (inclusive) the date from 3 months ago.
var dt = payload_object.AttendancePermissionBO.permissionList
    .Where(x => x.empNum == empNum
        && x.permDate >= threeMonthsAgoDate.Date)
    .OrderBy(x => x.permDate)
    .ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading