I am a bit lost on how to do this. I know how to initialize an array with values at the time of declaration. But how would I do it with a DateTime type array since it takes multiple arguments to create a date?
You mean like this?
DateTime[] dateTimes = new DateTime[]
{
new DateTime(2010, 10, 1),
new DateTime(2010, 10, 2),
// etc
};
DateTime [] startDate = new DateTime[5];
startDate[0] = new DateTime(11, 11, 10);
startDate[1] = new DateTime(11, 11, 10);
startDate[2] = new DateTime(11, 11, 10);
startDate[3] = new DateTime(11, 11, 10);
startDate[4] = new DateTime(11, 11, 10);
If you want to build an array for time span between two dates you could do something like this:
timeEndDate = timeStartDate.AddYears(1); // or .AddMonts etc..
rangeTimeSpan = timeEndDate.Subtract(timeStartDate); //declared prior as TimeSpan object
rangeTimeArray = new DateTime[rangeTimeSpan.Days]; //declared prior as DateTime[]
for (int i = 0; i < rangeTimeSpan.Days; i++)
{
timeStartDate = timeStartDate.AddDays(1);
rangeTimeArray[i] = timeStartDate;
}
For example, i want to add a DateTime array of 4 elements: DateTime[] myarray=new DateTime [4]; //the array is created
int year, month, day; //variables of date are created
for(int i=0; i<myarray.length;i++)
{
Console.WriteLine("Day");
day=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Month");
month=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Year");
year=Convert.ToInt32(Console.ReadLine());
DateTime date =new DateTime(year,month,day); //here is created the object DateTime, that contains day, month and year of a date
myarray[i]=date; //and then we set each date in each position of the array
}
DateTime [] "name_of_array"=new Date[int lenght_of_the_array]; //this is the array DateTime
And then when you assign the value in each position of the array:
DateTime "name_of_each_element_of_the_array"= new DateTime(int value_of_year,int value_of_month, int value_of_day);//this is each element that is added in each position of the array
Related
I want to find the date range which falls in input date, following is structure
public class Duration
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
var durations = new List<Duration>();
var duration1 = new Duration()
{
StartDate = new DateTime(2017, 08, 1),
EndDate = new DateTime(2017, 08, 10)
};
durations.Add(duration1);
var duration2 = new Duration()
{
StartDate = new DateTime(2017, 08, 5),
EndDate = new DateTime(2017, 08, 10)
};
durations.Add(duration2);
var duration3 = new Duration()
{
StartDate = new DateTime(2017, 08, 5),
EndDate = new DateTime(2017, 08, 6)
};
durations.Add(duration3);
Now I want to find duration which is closest to the entered date for list of <Durations> with LINQ or for-loop
My expected result for currentDate=new DateTime(2017, 08, 7); is duration2
You first need to check if the currentDate is within the start and end dates of each range. For the ones that meet that condition, you calculate the "closeness" adding both distances. When you find one lapse(gap) smaller tan the previous, you save its index... and voilá
int lapse = Integer.MaxValue;
int counter = 0;
int index = 0;
foreach (d in durations) {
if (((d.StartDate <= currentDate) && (d.EndDate >= currentDate))) {
int newlapse = ((currentDate - d.StartDate).TotalDays + (d.EndDate - currentDate).TotalDays);
if ((newlapse < lapse)) {
lapse = newlapse;
index = counter;
}
}
counter +=1;
}
return durations(index);
If you need the middle of interval to be closest:
durations.OrderBy((d) => Math.Abs(d.EndDate.Ticks + d.StartDate.Ticks) / 2 - currentDate.Ticks).FirstOrDefault();
If you need the start of interval to be closest:
durations.OrderBy((d) => Math.Abs(d.EndDate.Ticks - currentDate.Ticks)).FirstOrDefault();
As D le mentioned above
First check if currentDate is within the start and end dates
Second select the duration with the minimal difference between start end end date
I used a nuget package called morelinq which gives nice extensions methods like MinBy:
var result = (from d in durations
where (d.StartDate <= currentDate && d.EndDate >= currentDate)
select d).MinBy(d => d.EndDate - d.StartDate);
I want to calculate a list of months in specified date range.
For instance:
DateTime StartDate = 24 - 11 - 2014;
DateTime EndDate = 24 - 11 - 2016;
I want to calculate all the months between starting and ending date with names of months.
Here you go a static function that do what you need:
public static Dictionary<int, string> MonthsBetween(
DateTime startDate,
DateTime endDate)
{
DateTime iterator;
DateTime limit;
if (endDate > startDate)
{
iterator = new DateTime(startDate.Year, startDate.Month, 1);
limit = endDate;
}
else
{
iterator = new DateTime(endDate.Year, endDate.Month, 1);
limit = startDate;
}
var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
var result = new Dictionary<int, string>();
while (iterator <= limit)
{
if (!result.Keys.Contains(iterator.Month))
result.Add(iterator.Month, dateTimeFormat.GetMonthName(iterator.Month));
iterator = iterator.AddMonths(1);
}
return result;
}
you can use it like this:
DateTime startDate = new DateTime(2014, 11, 24);
DateTime endDate = new DateTime(2016, 11, 24);
var list = Program.MonthsBetween(startDate, endDate);
list variable contains dictionary with month int value and name according to CultureInfo.CurrentCulture of your program.
I get this function from this answer and slightly modify it.
DateTime[] s = new DateTime { "2000:1:1", "2001:1:1", "2002:1:1", "2003:1:1" };
DateTime[] e = new DateTime { "2000:2:1", "2001:2:1", "2002:2:1", "2003:2:1" };
cannot initialize type System.DateTime with a collection initializer because it does not implement System.Collections.IEnumerable
You are putting a string in a DateTime[], just put DateTime structs in a DateTime[]:
DateTime[] s = new DateTime[] { new DateTime(2000,1,1), new DateTime(2000,1,1), new DateTime(2000,1,1), new DateTime(2000,1,1) };
You cannot convert strings to DateTime objects implicitly. And you are missing the double square brackets after new DateTime.
You should do:
DateTime[] s = new DateTime[] { new DateTime(2000,1,1), new DateTime(2001,1,1), ....}
Works ok ... Try:
DateTime[] e = { new DateTime(), DateTime.Now, DateTime.Now.AddHours(3)};
You can write it like this :
DateTime[] s = { new DateTime(2000, 1, 1), new DateTime(2001, 1, 1), new DateTime(2002, 1, 1), new DateTime(2003, 1, 1) };
Lets say I 2 longs a start and end, which are really two date times converted to ticks. How would I tell if these two values overlap?
As MPelletier mentioned: you need two pairs of DateTimes:
var start1 = new DateTime(2013, 4, 10).Ticks;
var end1 = new DateTime(2013, 4, 20).Ticks;
var start2 = new DateTime(2013, 4, 9).Ticks;
var end2 = new DateTime(2013, 4, 11).Ticks;
if (start2 < end1)
{
//// Overlapping
}
I am stuck for sometime now, now need your help.
I want to display in a dropdown only fourth Sunday of each month, say from 1-Sep-2010 to 31-Aug-2011
I only want fourth Sunday in dropdown list, how to do it using asp.net C#
Regards
Here is an approach that uses a little LINQ and the knowledge that the fourth Sunday will occur between the 22nd and 28th of a month, inclusive.
DateTime startDate = new DateTime(2010, 9, 1);
DateTime endDate = startDate.AddYears(1).AddDays(-1);
List<DateTime> fourthSundays = new List<DateTime>();
DateTime currentDate = startDate;
while (currentDate < endDate)
{
// we know the fourth sunday will be the 22-28
DateTime fourthSunday = Enumerable.Range(22, 7).Select(day => new DateTime(currentDate.Year, currentDate.Month, day)).Single(date => date.DayOfWeek == DayOfWeek.Sunday);
fourthSundays.Add(fourthSunday);
currentDate = currentDate.AddMonths(1);
}
You can then bind that List<DateTime> to the dropdown or skip the list itself in favor of adding the items as you generate them to the dropdown, like below.
yourDropdown.Items.Add(new ListItem(fourthSunday.ToString()));
For giggles, you can do the whole thing in a LINQ statement and skip (most of) the variables.
DateTime startDate = new DateTime(2010, 9, 1);
IEnumerable<DateTime> fourthSundays =
Enumerable.Range(0, 12)
.Select(item => startDate.AddMonths(item))
.Select(currentMonth =>
Enumerable.Range(22, 7)
.Select(day => new DateTime(currentMonth.Year, currentMonth.Month, day))
.Single(date => date.DayOfWeek == DayOfWeek.Sunday)
);
Got bored so here you go. Two helper methods one retrieves the Week if it exist, and the other iterates through the months
class Program
{
static void Main(string[] args)
{
DateTime startDate = new DateTime(2010, 09, 1);
foreach(DateTime dt in EachMonth( new DateTime(2010, 09, 1), new DateTime(2011, 09, 1))){
DateTime? result = GetDayByWeekOffset(DayOfWeek.Sunday, dt, 4);
Console.WriteLine("Sunday:" + (result.HasValue?result.Value.ToString("MM-dd-yyyy"):"null"));
}
Console.ReadKey();
}
public static DateTime? GetDayByWeekOffset(DayOfWeek day, DateTime month, int weekOffSet)
{
//First day of month
DateTime firstDayOfMonth = month.AddDays((-1 * month.Day) + 1);
//
int daysOffSet;
daysOffSet= ((int)day + 7 - (int)firstDayOfMonth.DayOfWeek) % 7;
DateTime firstDay = month.AddDays(daysOffSet);
// Add the number of weeks specified
DateTime resultDate = firstDay.AddDays((weekOffSet - 1) * 7);
if (resultDate.Month != firstDayOfMonth.Month){
return null;
}else{
return resultDate;
}
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date; month = month.AddMonths(1))
yield return month;
}
}
Anthony's answer above is nice, I like it a lot. As an alternate, here is a method which is parameterized for the day of the week and the week number (i.e. if you need other combinations, like 4th Sunday, 3rd Friday, etc.) with some comments.
Call it like this for your case:
List<DateTime> sundays = DateInstances(new DateTime(2010, 9, 1), new DateTime(2011, 8, 31), DayOfWeek.Sunday, 4);
And the method itself:
public List<DateTime> DateInstances(DateTime start, DateTime end, DayOfWeek day, int weeks)
{
if (start > end)
throw new ArgumentOutOfRangeException("end", "The start date must occur before the end date");
List<DateTime> results = new List<DateTime>();
DateTime temp = start;
while (temp < end)
{
DateTime firstWeekday = new DateTime(temp.Year, temp.Month, 1);
//increment to the given day (i.e. if we want the 4th sunday, we must find the first sunday of the month)
while (firstWeekday.DayOfWeek != day)
firstWeekday = firstWeekday.AddDays(1);
//add the number of weeks (note: we already have the first instance, so subtract 1)
firstWeekday = firstWeekday.AddDays(7 * (weeks - 1));
//make sure we haven't gone over to the next month
if (firstWeekday.Month == temp.Month)
results.Add(firstWeekday);
//let's not loop forever ;)
temp = temp.AddMonths(1);
}
return results;
}