Home > database >  Loop through current month to next month in c#
Loop through current month to next month in c#

Time:09-24

I am facing a problem, logic written in my program is below

DataSet dslsip = mAE_Repo.FetchLastDayCustEmailsEquity_SIP_Content();
var ressip = (from r in dslsip.Tables[0].AsEnumerable() select r.Field<string>("emailid")).ToList();

var resdate = (from r in dslsip.Tables[0].AsEnumerable() select r.Field<DateTime>("a_confirmdatetime")).ToList();

//var datetime = DateTime.Now;

//List<string> date = new List<string>();
//List<DateTime> date = new List<DateTime>();

if (!ReferenceEquals(resdate,null) && resdate.Count>0)
{
    for (int i = 0; i < resdate.Count()-1; i  )
    {
        if (resdate[i].Month == DateTime.Now.Month || resdate[i].Month < DateTime.Now.Month)
        {
            //Logic should write here 

            //var das = DateTime.Now.AddMonths(1).ToString("MM");
            //var datet = resdate[i].AddMonths(1).ToString("MM");
        } 
    }
}

In the above code 'resdate' variable I'm fetching the list of the dates

Fetching the datelist

And the concept is I should add the month (current next month) Ex: {05-07-2021 00:00:00} I should add the (current month is 9 and next month is 10) so it should be {05-10-2021 00:00:00}

I'm not sure how to add the month only. I'm new to coding. Please help me in this.

CodePudding user response:

Use AddMonths() function, example:

new DateTime(DateTime.Now.AddMonths(1).Year, 
             DateTime.Now.AddMonths(1).Month, 
             d.Day);

Output:

10/5/2021 12:00:00 AM
10/1/2021 12:00:00 AM

CodePudding user response:

You need to change Month from date list. So, you can do it by using AddMonths() API. Used below Sample :

if (resdate[i].Month == DateTime.Now.Month || resdate[i].Month < DateTime.Now.Month)
{
   //Logic should write here 
   var datet = new DateTime(resdate[i].Year, DateTime.Now.AddMonths(1).Month, resdate[i].Day, resdate[i].Hour, resdate[i].Minute, resdate[i].Second);
}

Here we modified only month data As you wanted.

  • Related