Adding the difference of two dates to another date, avoiding leap year - c#

My goal is to figure out the difference between two dates and then add that amount of days to the original start.
DateTime originalStart = new DateTime(2015, 1, 1);
DateTime newDate = originalStart.AddDays((endDate - startDate).TotalDays);
For example with the following params:
original start: 1/1/2015
start date: 1/1/2016
end date: 1/1/2017
newDate should be: 1/1/2016 (difference between start and end is 1 year so then we add that one year to original start)
My problem is that if a leap year is part of the date difference between endDate and startDate and then I go and add those days to originalStart. I end up with dates like 1/2/2016 for newDate.
Any idea how I can avoid leap years here to make sure if the difference between 1/1/2016 and 1/1/2017 is rounded. I would only like to add exactly one year to originalStart and not the extra day because of the leap year.

DateTime originalStart = new DateTime(2015, 1, 1);
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime endDate = new DateTime(2016, 1,1);
endDate .Dump();
DateTime startDate= new DateTime(2017, 1,1);
startDate.Dump();
TimeSpan span = startDate- endDate ;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
int months = (zeroTime + span).Month - 1;
int days = (zeroTime + span).Day;
years.Dump();
months.Dump();
days.Dump();
originalStart= originalStart.AddMonths(months);
originalStart = originalStart.AddYears(years);
originalStart = originalStart.AddDays(days);

Related

How to get a list of all possible Periods (with start Date and end Date) by day interval from another Start-Date and End-Date in C# [duplicate]

This question already has answers here:
Create an array or List of all dates between two dates [duplicate]
(4 answers)
Split date range into date range chunks
(8 answers)
Closed 3 years ago.
I have a start Date : 01-01-2019 and End-Date 31-12-2019
I need to get all possible periods between those dates, but by interval.
Interval can be 180, 90, 45, 15 , 7 and 1 days.
So if I select 180 days return should be a list with those periods:
01/01/2019 - 30/06/2019 (First period of generated list )
01/07/2019 - 31/12/2019 (Second period of generated list )
It is almost like Generate list of list for start and end date of week from date range
But I need do this in C#
How to find a list of Dates from a Start-Date and End-Date
Is not quite What I need. But is close.
DateTime startDate = DateTime.Parse("01/01/2019");
DateTime endDate = DateTime.Parse("31/12/2019");
dayInterval = 45;
startDate = startDate.AddDays(dayInterval);
endDate = endDate.AddDays(-dayInterval);
I also tried:
var startDate = new DateTime(2019, 1, 1);
var endDate = new DateTime(2019, 12, 31);
int days = 45;
List<DateTime> range = Enumerable.Range(0, days)
.Select(i => startDate.AddDays(i))
.ToList();
Maybe try write that code like this:
tatic IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startDate, DateTime endDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startDate; i <= endDate; i = i.AddDays(45))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}
The solution proposed here is what I need Split date range into date range chunks
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}

Datetime substraction from DateTime value in c#

How to subtract "year=117 month=1 day=28 hour=7 min=43 sec=10" from a DateTime in c#?
I have already tried like below
split the string using regex.
add each item with -ve sign to a current DateTime value.
But I think it's not an efficient way.
Can anyone help me?
You can use below Code as per you requirement to get desired Result. Replace your Date, Time, year values in "new System.DateTime(1996, 6, 3, 22, 15, 0);"
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
you can try DateTime's subtraction.
for that first you have to make valid DateTime object from your information and then subtract that date from current date.
see below code,
int year = 117, month = 01, day = 28;
int hour = 07, minute = 43, second = 10;
DateTime timeToSubtract =
new DateTime(year > 0? year : 1, month > 0 ? month : 1, day > 0 ? day : 1, hour, minute, second);
DateTime subtractedDate =
new DateTime((DateTime.Now - timeToSubtract).Ticks);
as you can see, we are creating a date time object with information we have (date and time which should be subtracted form current date time) by, new DateTime(year, month, day, hour, minute, second) and then subtracting this from DateTime.Now, and then creating final date out of result of this subtraction.
here in last line we are creating a date (of past). this date is of specified time ago.

How to get date of a day in a week in C#

I am trying to get Date of a specific day based on its sequence in a week like
GetDate(22, 4);
which needs to return the date of 4th day in 22nd weeks of current year. How can I do this?
void Main()
{
int months;
var year = DateTime.Now.ToString("yyyy");
months = GetWeeksInYear( Convert.ToInt32(year));
Console.WriteLine(months);
}
public int GetWeeksInYear(int year)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime date1 = new DateTime(year, 12, 31);
Calendar cal = dfi.Calendar;
return cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}
public int GetDate(int weekNo, int dayNo)
{
return // Date
}
You can just add the number of days from the beginning of the year:
var dt = new DateTime(year, 1, 1);
dt = dt.AddDays(weekNo * 7 + dayNo);
var date = dt.Date;
I think a simple way would be to take Jan 1 of year and add number of days,
DateTime day = new DateTime(year, 1, 1).AddDays((week * 7) + days);
firstable the week of the year is a calendar calculation and locale dependent value so you have to consider that when giving the week number...
So you are for sure missing the use of something like
CultureInfo.CurrentCulture.Calendar;

How can I calculate the numbers of month between two dates in C#

I would like to know how to calculate the numbers of Month between two dates. Is there any method to calculate it in C#?
Eg1. Date1 = "2011/11/01"
Date2 = "2012/02/01"
Result. Numbers of Month =3
Eg2. Date1 = "2012/01/31"
Date2 = "2012/02/01"
Result. Numbers of Month =1
Eg3. Date1 = "2012/01/01"
Date2 = "2012/02/28"
Result. Numbers of Month =1
This will give difference between months:
int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;
My Noda Time project provides for this:
LocalDate date1 = new LocalDate(2011, 11, 1);
LocalDate date2 = new LocalDate(2012, 2, 1);
Period period = Period.Between(date1, date2, PeriodUnits.Months);
long months = period.Months; // 3
See the project documentation for arithmetic for more information.

Select Only Fourth Sunday of each month

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;
}

Categories