How to calculate a multiple date difference like
startDate1=("dd-MM-yy") 20-08-2011
endDate1=25-08-11
another
startdate2=27-08-2011
endDate2=30-08-2011
such that output will be
(endDate1-startDate1)+(endDate2-StartDate2) == 8days //only in terms of days
Use TimeSpan to calculate date difference.
Eg:
TimeSpan ts = Date1 - Date2;
int numberOfDays = ts.Days;
More info can be found here
Date - or + Date will return TimeSpan, it has a property named "Days" is what you need.
((endDate1-startDate)+(endDate2-StartDate2)).Days
Try this code :-
DateTime d1 = StarDate
DateTime d2 = EndDate;
TimeSpan t1 = d2.Subtract(d1);
days = t1.Days;
hours = t1.Hours;
Try this,
DateTime strdate = Convert.ToDateTime("1/1/2011");
DateTime enddate = Convert.ToDateTime("1/10/2011");
DateTime strdate1 = Convert.ToDateTime("1/1/2011");
DateTime enddate1 = Convert.ToDateTime("1/10/2011");
int resultdays = (enddate.Subtract(strdate) + enddate1.Subtract(strdate1)).Days;
Complete Code/Answer....
public class DateController : Controller
{
public ActionResult date()
{
int allDiff;
List<int> list=new List<int>();
int flag = 0;
int conflict = 0;
List<int> conf = new List<int>();
conf.Add(0);
int a = 0;
DateTime[] startDate = new DateTime[3];
startDate[0] = new DateTime(2011, 11, 5);
startDate[1] = new DateTime(2011, 11,7);
startDate[2] = new DateTime(2011, 11, 15);
DateTime[] endDate = new DateTime[3];
endDate[0] = new DateTime(2011, 11, 10);
endDate[1] = new DateTime(2011, 11,12);
endDate[2] = new DateTime(2011, 11, 20);
DateTime Min= startDate.Min();
DateTime Max = endDate.Max();
TimeSpan span = Max - Min;
int total = span.Days;
ViewBag.globalTotal = total;
foreach (DateTime e in endDate)
{
foreach (DateTime s in startDate)
{
if (s >= e)
{
TimeSpan span1 = s - e;
allDiff = span1.Days;
list.Add(allDiff);
flag = 1;
conflict = 1;
}
else {
flag = 0;
}
}
if((list.Count==1)&&(conflict==1)&&(list!=null)){
a = list[0];
conf.Add(a);
}
if ((flag == 1)&&(list.Count>1))
{
int m = list.Min();
ViewBag.dhiraj = m;
total = total - m;
list.Clear();
}
}
int confl= conf.Min();
total=total-confl;
ViewBag.Total = total;
return View();
}
}
`
If you want the exact DateDiff function as it works in SQL, you can remove time stamp of the Date variables and then Subtract one from another. It will give u exact number of days.
Ex.
DateTime dt = DateTime.Parse(fromDate.ToShortDateString());
DateTime dt1 = DateTime.Parse(toDate.ToShortDateString());
int noOfDays = dt.Subtract(dt1).TotalDays;
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.
I have 2 datetime format as departure date and arrival date, such as 25/04/2014 as a departure and 22/04/2014 as an arrival, now I wish to return the dates between those two as following: 22/04/2014|23/04/2014|24/04/2014|25/04/2014 in C#, do you have any idea for this?
You could avoid to type a loop using Linq
StringBuilder sb = new StringBuilder();
DateTime arrival = new DateTime(2014,4,22);
DateTime departure = new DateTime(2014,4,25);
int days = Convert.ToInt32((departure - arrival).TotalDays);
var rng = Enumerable.Range(0,days+1).ToList();
rng.ForEach(r => sb.Append(arrival.AddDays(r).ToShortDateString() + "|"));
sb.Length--;
Console.WriteLine(sb.ToString());
var startDate = new DateTime(2014, 4, 22);
var endDate = new DateTime(2014, 4, 25);
var sb = new StringBuilder();
while (startDate <= endDate)
{
sb.AppendFormat("|{0}", startDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
startDate = startDate.AddDays(1);
}
Console.WriteLine(sb.ToString().Substring(1));
See it in action
Like:
var startDate = new DateTime(2014, 04, 25);
var endDate = new DateTime(2014, 04, 29);
var currentDate = startDate;
while (currentDate <= endDate)
{
Console.WriteLine(currentDate);
currentDate = currentDate.AddDays(1);
}
...but with proper formatting, but this would be view-logic.
VoilĂ :
DateTime start = new DateTime(2014, 4, 24);
DateTime end = new DateTime(2014, 4, 22);
DateTime current = start < end ? start : end;
DateTime stop = start < end ? end : start;
List<DateTime> dates = new List<DateTime>();
while (current <= stop)
{
dates.Add(current);
current = current.AddDays(1);
}
StringBuilder sb = new StringBuilder();
foreach (DateTime dt in dates)
{
if (sb.Length > 0)
sb.Append("|");
sb.Append(dt.ToString("dd/MM/yyyy"));
}
Console.WriteLine(sb.ToString());
I've a date list
StartDate EndDate
1-Nov-2011 31-Jan-2012
3-Mar-2012 1-Apr-2012
1-May-2012 31-Dec-2012
1-Jan-2013 1-Dec-2013
Get all the records which falls in this range
1-Jan-2012 31-Dec-2012
The answer would be the first three records from the above list
How could i do it using Linq.
Thanks
This should work:
var rangeStart = new DateTime(2012, 1, 1);
var rangeEnd = new DateTime(2012, 12, 31);
var res = list
.Where(item => (item.StartTime < rangeStart ? rangeStart : item.StartTime) < (item.EndTime < rangeEnd ? item.EndTime : rangeEnd) )
.ToList();
The condition is "the larger of the two left ends needs to be less than the smaller of the two right ends".
I Suggest the following wrapper
public struct DateInterval
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool HasIntersection(DateInterval secondInterval)
{
return HasIntersection(this.StartDate, this.EndDate,secondInterval.StartDate,secondInterval.EndDate);
}
private bool HasIntersection(DateTime dateStart1, DateTime dateEnd1, DateTime dateStart2, DateTime dateEnd2)
{
if (dateEnd1 < dateStart2) return false;
if (dateEnd2 < dateStart1) return false;
return true;
}
}
usage:
var targetInterval = new DateInterval() {StartDate = new DateTime(2012, 1, 1), EndDate = new DateTime(2012, 1, 1)};
var listOfIntervals =GetIntervals();//retrieve data
var filteredList = listOfIntervals.Where(targetInterval.HasIntersection).ToList();
I've two dates
21/01/2011 [From Date]
25/01/2011 [To Date]
How can I get all the dates between these ranges using c#
The answer should be
21/01/2011 22/01/2011
23/01/2011 24/01/2011
25/01/2011
var allDates = Enumerable.Range(0, int.MaxValue)
.Select(x => fromDate.Date.AddDays(x))
.TakeWhile(x => x <= toDate.Date);
I'm sure this can help you:
http://geekswithblogs.net/thibbard/archive/2007/03/01/CSharpCodeToGetGenericListOfDatesBetweenStartingAndEndingDate.aspx
var dateArr = new List<DateTime>();
for (var date = startDate; date <= endDate; date = date.AddDays(1)) {
dateArr.Add(date);
}
Now dateArr contains your required dates.
public System.Collections.Generic.IEnumerable<DateTime> GetDatesBetween(
DateTime start,
DateTime end
)
{
DateTime current = start;
while (current <= end)
{
yield return current.Date;
current = current.AddDays(1);
}
}
should do the job
[edit] Added the .Date to "round" the date to midnigth
How about:
var startDT = new DateTime(2011, 01, 21);
var endDT = new DateTime(2011, 01, 25);
var workDT = startDT;
do
{
Console.WriteLine(workDT.ToString("dd/MM/yyyy"));
workDT = workDT.AddDays(1);
} while (workDT <= endDT);
Console.ReadLine();
I dont know if we have anything to do this inbuilt in Framework but you can try this:
DateTime dt1 = new DateTime(2011,01,21);
DateTime dt2 = new DateTime(2011,01,25);
List<DateTime> datetimerange = new List<DateTime>();
while(DateTime.Compare(dt1,dt2) <= 0)
{
datetimerange.Add(dt1);
dt1 = dt1.AddDays(1);
}
if (toDate < fromDate)
return;
var days = (new DateTime[(toDate - fromDate).Days + 1).
Select((x, i) => fromDate.AddDays(i));