Loop through current month to next month in c# - c#

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
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.

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

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

How can I get the date of selected week which are in the date range selected

how can I get the date of selected week which are in the date range selected in C#.
I am new in C#, please help me out to save these dates in DB, which comes under the date range
You could make all the possible Dates between the ranges and then check against a list of DaysOfWeeks:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var selectedDayOfWeeks = new List<DayOfWeek>{DayOfWeek.Thursday, DayOfWeek.Saturday};
var startDate = new DateTime(2017, 10, 24);
var endDate = new DateTime(2017, 10, 28);
var possibleDates = new List<DateTime>();
for(var current = startDate; current <= endDate; current= current.AddDays(1))
{
if(selectedDayOfWeeks.Contains(current.DayOfWeek))
{
possibleDates.Add(current);
}
}
foreach(var d in possibleDates){
Console.WriteLine(d);
}
}
}
This is one way...
var from = DateTime.Parse("10/24/2018");
var to = DateTime.Parse("11/14/2018");
var dayList = new List<DateTime>();
for (var day = from.Date; day.Date <= to.Date; day = day.AddDays(1))
{
if
(
day.DayOfWeek == DayOfWeek.Monday ||
day.DayOfWeek == DayOfWeek.Wednesday ||
day.DayOfWeek == DayOfWeek.Friday ||
day.DayOfWeek == DayOfWeek.Sunday
)
{
dayList.Add(day);
}
}
DayOfWeek is an enumeration in the system namespace, you can determine your day of week check box and add a corresponding enum value to a list of DayOfWeek and use as Kevin Smith demonstrated
var selectedDaysOfWeek = new List<DayOfWeek>();
var from = DateTime.Parse("10/24/2018");
var to = DateTime.Parse("11/14/2018");
var dayList = new List<DateTime>();
if (checkBoxMonday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Monday); }
if (checkBoxTuesday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Tuesday); }
if (checkBoxWednesday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Wednesday); }
if (checkBoxThursday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Thursday); }
if (checkBoxFriday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Friday); }
if (checkBoxSaturday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Saturday); }
if (checkBoxSunday.IsChecked) { selectedDaysOfWeek.Add(DayOfWeek.Sunday); }
for (var day = from.Date; day.Date <= to.Date; day = day.AddDays(1))
{
if (selectedDaysOfWeek.Contains(day.DayOfWeek))
{
dayList.Add(day);
}
}
foreach(var day in dayList)
{
// Add to day to DB
}

How to assign unique Employee on weekends in C#

I have a list of 7 employees. I am iterating a loop of dates for the current month and want to assign two employees on each date, but on weekends they should not repeat until all employees are being assigned. For Example: I am having seven employees:
John
Sophia
Olivia
Davis
Clark
Paul
Thomas
Now my date loop is:
for (int i = 0; i < dates.Length; i++)
{
DateTime newDate = new DateTime();
newDate = dates[i];
/*if(newdate == "Saturday")
var EmpName1 = emplist[i];
var EmpName2 = emplist[i];*/
}
In the above loop I want to assign two employees each on Saturday and Sunday until all other have not been assigned previously. Something like this:
4th March: John and Sophia
5th March: Olivia and Davis
11th March: Clark and Paul
12th March: Thomas and John
and so on.... John will not be assigned till all of them are assigned. After that the list will start again. Can anyone help me on this?
Use a separate index for the person to chose every time you need to chose one.
After selecting, change the index with:
index = (index + 1) % employees.Length // Number fo employees
The % (means modulo) makes sure the counter starts at 0 again when employees.Length is reached.
So something like:
var empIndex = 0;
for (int i = 0; i < dates.Length; i++)
{
DateTime newDate = new DateTime();
newDate = dates[i];
if(newdate == "Saturday") // and Sunday, use or: || (newData == "Sunday"))
{
var EmpName1 = emplist[empIndex];
empIndex = (empIndex + 1) % empList.Length;
var EmpName2 = emplist[empIndex];
empIndex = (empIndex + 1) % empList.Length;
}
}
Seems to me that this boils down to ordering the employees by DateOfLastWeekendOnCall?
var e = Employees.OrderBy(i=>i.DateOfLastWeekendOnCall).First();
e.DateOfLastWeekendOnCall = weekendThatNeedsAssigning;
Explaination:
"dont assign the employee until all other employees have also been assigned"
is equivalent to
"assign the employee whose maximum date assigned to is the lowest of all employees (or who has never been assigned)"
So if you keep track of the last Saturday each employee was assigned to, its trivial to see which employee you should assign to the next date.
You can put in some special logic to handle the null case, or just put in MinDate as a default value
You could use a queue:
var weekendWarriors = new Queue<string>();
CheckRefreshQueue<string>(weekendWarriors, employees);
for (int i = 0; i < dates.Length; i++)
{
DateTime newDate = new DateTime();
newDate = dates[i];
if (newDate.DayOfWeek == DayOfWeek.Saturday || newDate.DayOfWeek == DayOfWeek.Sunday)
{
string emp1;
string emp2;
CheckRefreshQueue<string>(weekendWarriors, employees);
emp1 = weekendWarriors.Dequeue();
CheckRefreshQueue<string>(weekendWarriors, employees);
emp2 = weekendWarriors.Dequeue();
}
}
Here's CheckRefreshQueue:
private static void CheckRefreshQueue<T>(Queue<T> toRefresh, IEnumerable<T> fromCollection)
{
if (toRefresh.Count == 0) foreach (T item in fromCollection) toRefresh.Enqueue(item);
}

Get next Hannukah date in C#

I am trying to find out from today's UTC date the date of the next Hannukah.
I already found that C# has HebrewCalendar class and I was able to get the current Jewish date with GetYear(), GetMonth()andGetDayOfMonth(). But don't really know how to work with this information to get the Jewish date that is gonna happen next for the current date.
Hannukah is dated on 25th of Kislev (3rd month in Jewish calendar).
#DmitryBychenko's answer is fine, although if you don't want to loop, you can also calculate it:
var calendar = new HebrewCalendar();
var result = DateTime.UtcNow;
if(
calendar.GetMonth(result) < 3
|| (calendar.GetMonth(result)==3 && calendar.GetDayOfMonth(result)<25)
)
result = new DateTime(calendar.GetYear(result), 3, 25, calendar);
else
result = new DateTime(calendar.GetYear(result)+1, 3, 25, calendar);
If you are under 25/3 on the HebrewCalendar, use this year, else use next
Result is also 7 Dec 2015 in the gregorian calendar
If (as per the comments) you don't want those pesky if statements for some reason, you could do something like:
var calendar = new HebrewCalendar();
var result = DateTime.UtcNow;
var addYear = (calendar.GetMonth(result) < 3 || (calendar.GetMonth(result)==3 && calendar.GetDayOfMonth(result)<25)) ? 0 : 1;
result = new DateTime(calendar.GetYear(result) + addYear, 3, 25, calendar);
I don't think this helps readability but there you go
As it was suggested on Twitter, here's a Noda Time solution:
// As of 2.0, it will be CalendarSystem.HebrewCivil
var calendar = CalendarSystem.GetHebrewCalendar(HebrewMonthNumbering.Civil);
var today = SystemClock.Instance.InZone(DateTimeZone.Utc, calendar).Date;
var thisHannukah = new LocalDate(today.Year, 3, 25, calendar);
return thisHannukah >= today ? thisHannukah : thisHannukah.PlusYears(1);
Alternative for the last two statements:
var year = today.Month < 3 || today.Month == 3 && today.Day <= 25
? today.Year : today.Year + 1;
return new LocalDate(year, 3, 25, calendar);
If we go ahead with feature request 317, this could be much simpler. For example:
// Putative API only! Doesn't work yet!
MonthDay hannukah = new MonthDay(3, 25, calendar);
var nextHannukah = hannukah.NextOrSame(today);
Eh, just looping? Testing date one by one starting from, say, DateTime.Now?
HebrewCalendar calendar = new HebrewCalendar();
DateTime result = DateTime.Now;
for (DateTime date = DateTime.Now.Date; ; date = date.AddDays(1)) {
if (calendar.GetDayOfMonth(date) == 25 && calendar.GetMonth(date) == 3) {
result = date;
break;
}
}
it returns result == 7 Dec 2015?

All Sundays in month, this month has no Sundays yet,issue

I have this code, it failed because thisMonthSundays are empty:
public ActionResult TradeUKKPISearchesData() //show dropdownlist in the view
{
var now = DateTime.Now;
var lastMonth = now.AddMonths(-1);
var thisMonthSundays = GetDatesOfSundays(now.Year, now.Month).OrderByDescending(x => x.Date);
var lastMonthSundays = GetDatesOfSundays(lastMonth.Year, lastMonth.Month).OrderByDescending(x => x.Date); //problem here, must add some sort of check here?
var sundaysToTakeFromLastMonth = 4;
var sundays = thisMonthSundays.Concat(lastMonthSundays.Skip(Math.Max(0, lastMonthSundays.Count() - sundaysToTakeFromLastMonth)).Take(sundaysToTakeFromLastMonth));
var allSundaysInThisMonth = new SundaysInMonthViewModel
{
AllSundays = sundays.Select(x => new SelectListItem
{
Value = x.ToString("dd/MM/yyyy"),
Text = x.ToString("dd/MM/yyyy"),
})
};
var selectedSunday = new SundaysInMonthViewModel
{
SelectedSunday = thisMonthSundays.Where(x => x <= now).Last() //failed here
};
return View(allSundaysInThisMonth);
}
private IEnumerable<DateTime> GetDatesOfSundays(int year, int month)
{
var ci = CultureInfo.InvariantCulture;
for (int i=1; i <= ci.Calendar.GetDaysInMonth(year, month); i++)
{
var date = new DateTime(year, month, i);
if ((date.DayOfWeek == DayOfWeek.Sunday) && (date <= DateTime.Now))
{
yield return date; //skips all for this month
}
}
}
I need to fix this, please help with ideas?
thanks
As the Octobar month do not have SUnday so far, the variable SelectedSunday is empty....
You can use LastOrDefault() instead :
SelectedSunday = thisMonthSundays.Where(x => x <= now).LastOrDefault() ;
Note : The Default value for DateTime Type is DateTime.Min which is 1/1/0001 12:00:00 AM.
There are some mistakes in your code here.
Using var is not something you want to do everywhere.
You should never use arbitrary values in your functions. Instead of checking that the days are prior to today, you should add a limit parameter to your function and pass DateTime.Now
on the call.
Your function is already returning all the Sundays of a given month that are prior to today. Your Linq Request is just a replication of code and will return the whole collection every-time.
Since today is 10-01 and that we are Monday, there is no Sundays on October prior to today. This is why your collection is empty.

How to query current week & current month report by using LINQ to XML?

I am developing window phone 7 application in silverlight. I am new to the silverlight. I am also new to LINQ to XML. In my application the user select the date & submit some transaction details into the application. The details gets stored in XML File. I am using the custom date control in my application for the date selection as follows
private void DatePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
AppObj = Application.Current as App;
AppObj.date = (DateTime)EntryDate.Value;
}
Then the value of AppObj.date gets stored in the XML file. Sometimes I use the DateTime.Now to store the date in the XML File. Now I want to generate the report of submitted transaction details by querying through LINQ to XML. I want to generate the report for today's date, current week & current month. For today's date report I am using the following code
public class TransactionList : List<Transaction>
{
public void GetTransactionObjects(String strXMLFile, int Currency_ID, int TransactionType_ID)
{
XDocument doc = null;
XMLFileManager XMLDocObj = new XMLFileManager();
doc = XMLDocObj.LoadXMLFile(strXMLFile);
DateTime today = DateTime.Today;
var vTransaction = doc.Descendants("Transaction")
.Where(x => ((DateTime)x.Element("Current_Date")).Date == today)
.Where(x => x.Element("TransactionType_ID").Value == TransactionType_ID.ToString())
.Where(x => x.Element("Currency_ID").Value == Currency_ID.ToString())
.Select(x => new Transaction(x));
this.Clear();
AddRange(vTransaction);
}
}
The Transaction class contains the following constructor.
public Transaction(XElement xElement)
{
Transaction_ID = Convert.ToInt32(xElement.Element("Transaction_ID").Value.ToString());
TransactionType_ID = Convert.ToInt32(xElement.Element("TransactionType_ID").Value.ToString());
Alphabet_ID = Convert.ToInt32(xElement.Element("Alphabet_ID").Value.ToString());
ID = Convert.ToInt32(xElement.Element("ID").Value.ToString());
SubCategory_ID = Convert.ToInt32(xElement.Element("SubCategory_ID").Value.ToString());
Item_ID = Convert.ToInt32(xElement.Element("Item_ID").Value.ToString());
Currency_ID = Convert.ToInt32(xElement.Element("Currency_ID").Value.ToString());
InputTypeMethod_ID = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Principle = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Interest = Convert.ToInt32(xElement.Element("Interest").Value.ToString());
ROI = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Amount = Convert.ToInt32(xElement.Element("Amount").Value.ToString());
//Current_Date = Convert.ToDateTime(xElement.Element("Current_Date").Value.ToString());
Current_Date = ((DateTime)xElement.Element("Current_Date")).Date;
}
In the XML File the value gets stored for date & time. The value gets stored as follows
<Transactions>
<Transaction>
<Transaction_ID>0</Transaction_ID>
<TransactionType_ID>0</TransactionType_ID>
<Alphabet_ID>3</Alphabet_ID>
<ID>0</ID>
<SubCategory_ID>0</SubCategory_ID>
<Item_ID>0</Item_ID>
<Currency_ID>3</Currency_ID>
<InputTypeMethod_ID>0</InputTypeMethod_ID>
<Principle>0</Principle>
<Interest>0</Interest>
<ROI>0</ROI>
<Amount>5000</Amount>
<Current_Date>2010-12-31T18:08:23.433+05:30</Current_Date>
</Transaction>
</Transactions>
Look at the node
2010-12-31T18:08:23.433+05:30
The date format is yyyy-mm-dd.
Now how should I write the following query to get all the submitted transaction details for current week as well as current month ?
var vTransaction = doc.Descendants("Transaction")
.Where(x => ((DateTime)x.Element("Current_Date")).Date == today)
.Where(x => x.Element("TransactionType_ID").Value == TransactionType_ID.ToString())
.Where(x => x.Element("Currency_ID").Value == Currency_ID.ToString())
.Select(x => new Transaction(x));
Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me.
The DateTime object has a property Month, with that you should be able to filter on month. For week you could use the GetWeekOfYear in the Calendar class, read this link: http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx
The following code will give the current week summary :
DateTime startDate = DateTime.Today.Date.AddDays(-(int)DateTime.Today.DayOfWeek), // prev sunday 00:00
endDate = startDate.AddDays(7); // next sunday 00:00
var vTransaction = from x in doc.Descendants("Transaction")
where ((DateTime)x.Element("Current_Date")).Date >= startDate
&& ((DateTime)x.Element("Current_Date")).Date < endDate
where x.Element("TransactionType_ID").Value == TransactionType_ID.ToString()
select new Transaction(x);
The Following code will give the current month summary
int CurrentYear = DateTime.Today.Year;
int CurrentMonth = DateTime.Today.Month;
DateTime startDate = new DateTime(CurrentYear, CurrentMonth, 1);
DateTime endDate = startDate.AddMonths(1).AddMinutes(-1);
var vTransaction = from x in doc.Descendants("Transaction")
where ((DateTime)x.Element("Current_Date")).Date >= startDate
&& ((DateTime)x.Element("Current_Date")).Date < endDate
where x.Element("TransactionType_ID").Value == TransactionType_ID.ToString()
select new Transaction(x);
OR both the queries can be wriiten for the current week of selected date & current month of selected date as follows
public void GetCurrentWeekSummary(String strXMLFile, int TransactionType_ID, DateTime selectedDate)
{
XDocument doc = null;
XMLFileManager XMLDocObj = new XMLFileManager();
doc = XMLDocObj.LoadXMLFile(strXMLFile);
DateTime startDate = selectedDate.Date.AddDays(-(int)selectedDate.DayOfWeek), // prev sunday 00:00
endDate = startDate.AddDays(7); // next sunday 00:00
var vTransaction = from x in doc.Descendants("Transaction")
where ((DateTime)x.Element("Current_Date")).Date >= startDate
&& ((DateTime)x.Element("Current_Date")).Date < endDate
where x.Element("TransactionType_ID").Value == TransactionType_ID.ToString()
select new Transaction(x);
}
public void GetCurrentMonthSummary(String strXMLFile, int TransactionType_ID, DateTime selectedDate)
{
XDocument doc = null;
XMLFileManager XMLDocObj = new XMLFileManager();
doc = XMLDocObj.LoadXMLFile(strXMLFile);
int CurrentYear = selectedDate.Year;
int CurrentMonth = selectedDate.Month;
DateTime startDate = new DateTime(CurrentYear, CurrentMonth, 1);
DateTime endDate = startDate.AddMonths(1).AddMinutes(-1);
var vTransaction = from x in doc.Descendants("Transaction")
where ((DateTime)x.Element("Current_Date")).Date >= startDate
&& ((DateTime)x.Element("Current_Date")).Date < endDate
where x.Element("TransactionType_ID").Value == TransactionType_ID.ToString()
select new Transaction(x);
}

Categories

Resources