How to get days in range - c#

I have two date time ranges 8/27/2011 and 8/31/2011 how i can make get all days ? like that : 8/28/2011, 8/29/2011 and 8/30/2011
thanks

Here is a code snippet to get all days between a start and end date inclusive:
DateTime today = new DateTime(2011, 8, 29);
DateTime nextWeek = new DateTime(2011, 9, 4);
TimeSpan difference = nextWeek - today;
List<DateTime> days = new List<DateTime>();
for (int i = 0; i <= difference.Days; i++)
{
days.Add(today.AddDays(i));
}
foreach (var dateTime in days)
{
Console.WriteLine(dateTime);
}
Console.ReadLine();
Output:
8/29/2011 12:00:00 AM
8/30/2011 12:00:00 AM
8/31/2011 12:00:00 AM
9/1/2011 12:00:00 AM
9/2/2011 12:00:00 AM
9/3/2011 12:00:00 AM
9/4/2011 12:00:00 AM

To piggy back off of davecoulter, if you need to do this all over your application for your DateTime objects, you might want to define an extenion method for your DateTime object.
void Main()
{
DateTime today = new DateTime(2011, 8, 29);
DateTime nextWeek = new DateTime(2011, 9, 4);
foreach (DateTime dateTime in today.ListAllDates(nextWeek))
{
Console.WriteLine(dateTime);
}
Console.ReadLine();
}
public static class DateTimeExtenions
{
public static IEnumerable<DateTime> ListAllDates(this DateTime lhs, DateTime futureDate)
{
List<DateTime> dateRange = new List<DateTime>();
TimeSpan difference = (futureDate - lhs);
for(int i = 0; i <= difference.Days; i++)
{
dateRange.Add(lhs.AddDays(i));
}
return dateRange;
}
}
You can copy this straight into LinqPad and run as program to test it out.

using System;
using System.Linq;
var startDate = new DateTime(2011, 9, 1);
var days = Enumerable.Range(0, 10).Select(n => startDate.AddDays(n));

Create a new date from both datetimes datetime to make sure that it they are at the start of the day. Then run a for loop that works from starttime.Ticks to endtime.Ticks and increments by TimeSpan.TicksPerDay and create a new DateTime that you add to a list for every value. The example below will not include the end date but you can easily fix that.
var start= new DateTime(2009,01,01).Ticks;
var end= new DateTime(2009,01,10).Ticks;
List<DateTime> dates = new List<DateTime>();
for (var i = start; i < end; i+=TimeSpan.TicksPerDay) {
dates.Add(new DateTime(i));
}
Or you could loop through between them and call the AddDays method.

Related

How to get interval between hours and put into list from start into finish?

For example, I will be given a time on hours with type DateTime hours like this
for the starter
my starttime is 00:00
endtime is 02:00
and every time 30 minutes I like to input the value into a List<DateTime>
so, how can I get the value to put into a list that is look like this?
00:00
00:30
01:00
01:30
02:00
My Code
DateTime starTime = new DateTime();
DateTime endTimes = new DateTime();
DateTime interval = new DateTime();
List<DateTime> intervals = new List<DateTime>();
starTime = DateTime.ParseExact(fulldate + "00:00",
"yyyy/MM/dd HH:mm",
CultureInfo.InvariantCulture);
endTimes = DateTime.ParseExact(fulldate + "02:00",
"yyyy/MM/dd HH:mm",
CultureInfo.InvariantCulture); ;
interval = starTime;
for (int i = 0; i < 24; i++)
{
interval.AddHours(0.5);
intervals.Add(interval);
if (interval.ToString("HH:mm") == endTimes.ToString("HH:mm"))
{
break;
}
}
Can anyone help me to solve this?
With some assumption (that end time is on the same day, that your end time is always something that can be devided by 30 mins, ...) this would work.
var start = new TimeSpan(0, 0, 0);
var end = new TimeSpan(2, 0, 0);
var current = start;
List<DateTime> values = new List<DateTime>();
var startDate = DateTime.Now.Date; // editited after #pinkflowydx33's comment
values.Add(startDate + start);
while (current < end)
{
current = current.Add(new TimeSpan(0, 30, 0));
values.Add(startDate + current);
}
foreach (var v in values)
{
Console.WriteLine(v);
}
i prepared that type of solution. - It's loop over number, which represent - times of valueToChange - in this specific case between 30 minutes - and add to the startDate - 30 minutes and also saving to list.
using System;
public class Program
{
public static void Main()
{
List<DateTime> intervals = new List<DateTime>();
var changeValue = 30;
var startDate = new DateTime(2010, 05, 12, 13, 00, 00);
var endDate = new DateTime(2010, 05, 12, 14, 00, 00);
var timeIntervals = System.Math.Abs(startDate.Subtract(endDate).TotalMinutes / changeValue);
for (int i = 0; i < timeIntervals; i++)
{
startDate.AddMinutes(30);
intervals.Add(startDate)
}
}
}
In this case the start and end date are divided by 30 minutes without rest - so if there will be 13:00 and 13:12 - it's doesn't add the value to List - cause the value doesn't > 30.

How calculate if a Date is 6 month later birthdate in C#

how can I calculate if a date (in DateTime format) is 6 month later or not from my BirthDate (in DateTime format)?
Use DateTime AddMonth method
https://msdn.microsoft.com/ru-ru/library/system.datetime.addmonths(v=vs.110).aspx
var dat = new DateTime(2015, 12, 31);
var dat2 = new DateTime(2015, 12, 31);
if (dat.AddMonths(6) < dat2) { ... }
You should use DateTime.AddMonths :
DateTime dt;
DateTime birthDate;
if (dt <= birthDate.AddMonths(6))
{
}
enter your birth date, calculate your next birthday and compare the dates,
var born = new DateTime(1900, 02, 01);
var checkdate = DateTime.Now;
var nextBirthday = new DateTime(DateTime.Now.Year, born.Month, born.Day);
if (nextBirthday < DateTime.Now)
{
nextBirthday = new DateTime(DateTime.Now.Year + 1, born.Month, born.Day);
}
if (checkdate.AddMonths(6) < nextBirthday)
{
Console.WriteLine("date is 6 months later then birthday");
}
else
{
Console.WriteLine("wait for it");
}
DateTime birthDate=new DateTime(year,month,day);
DateTime dateToCompare = new DateTime(year, month, day);
if(dateToCompare >= birthdate.AddMonths(6))
{
//DoSomething
}
You could calculte the difference between dates using Subtract method and calculate how many months you have between these dates, for sample:
DateTime birthDay = /* some date */;
DateTime someDate = /* some date */;
var months = someDate.Subtract(birthDay).Days / (365.25 / 12);
This answer provides a good helper for Dates:
https://stackoverflow.com/a/33287670/316799

Generating weekly dates

I am sure this has been done before so i am looking for an efficient solution instead of own custom solution.
Given 2 dates, I am trying to generate the accurate weekly date (for creating weekly orders).
EDIT: I need to use .NET standard library to do this.
Example below,
Given 28/02/2012 and 6/03/2012.
so, the weekly dates generated are
- Week From(Start Monday): Week To(End Sunday):
- 27/02/2012 - 04/03/2012
- 05/03/2012 - 11/03/2012
Another example (1 month)
Given 01/02/2012 and 29/02/2012
so, the weekly dates generated are
- Week From(Start Monday): Week To(End Sunday):
- 30/01/2012 - 05/02/2012
- 06/02/2012 - 12/02/2012
- 13/02/2012 - 19/02/2012
- 20/02/2012 - 26/02/2012
- 27/02/2012 - 04/03/2012
I am doing this in c#. Has this been done before? Mind sharing the solutions?
Cheers
Here's a solution using Noda Time. Admittedly it requires a <= operator which I'm just implementing right now - but that shouldn't take long :)
using System;
using NodaTime;
class Test
{
static void Main()
{
ShowDates(new LocalDate(2012, 2, 28), new LocalDate(2012, 3, 6));
ShowDates(new LocalDate(2012, 2, 1), new LocalDate(2012, 2, 29));
}
static void ShowDates(LocalDate start, LocalDate end)
{
// Previous is always strict - increment start so that
// it *can* be the first day, then find the previous
// Monday
var current = start.PlusDays(1).Previous(IsoDayOfWeek.Monday);
while (current <= end)
{
Console.WriteLine("{0} - {1}", current,
current.Next(IsoDayOfWeek.Sunday));
current = current.PlusWeeks(1);
}
}
}
Obviously it's possible to do this in normal DateTime as well, but there's no real representation of "just a date" which makes the code less clear - and you'd need to implement Previous yourself.
EDIT: For example, in this case you might use:
using System;
class Test
{
static void Main()
{
ShowDates(new DateTime(2012, 2, 28), new DateTime(2012, 3, 6));
ShowDates(new DateTime(2012, 2, 1), new DateTime(2012, 2, 29));
}
static void ShowDates(DateTime start, DateTime end)
{
// In DateTime, 0=Sunday
var daysToSubtract = ((int) start.DayOfWeek + 6) % 7;
var current = start.AddDays(-daysToSubtract);
while (current <= end)
{
Console.WriteLine("{0} - {1}", current, current.AddDays(6));
current = current.AddDays(7);
}
}
}
Assuming you don't have to figure out that the start date is a monday:
var slots = new List<Tuple<DateTime, DateTime>>();
DateTime start = new DateTime(2012, 2, 28);
DateTime end = new DateTime(2012, 3, 6);
for (DateTime i = start; i < end; i = i.AddDays(7))
{
slots.Add(new Tuple<DateTime, DateTime>(i, i.AddDays(6)));
}
foreach (var slot in slots)
{
Console.WriteLine("{0}\t{1}", slot.Item1.ToString("dd/MM/yyyy"), slot.Item2.ToString("dd/MM/yyyy"));
}
Edit: Assuming you have to figure out what monday and what sunday covers the date range, you can move one day backwards till you hit a monday, and a day forward till you hit a sunday.
class Program
{
static void Main(string[] args)
{
var slots = new List<Tuple<DateTime, DateTime>>();
DateTime start = FirstMonday(new DateTime(2012, 2, 28));
DateTime end = FirstSunday(new DateTime(2012, 3, 6));
for (DateTime i = start; i < end; i = i.AddDays(7))
{
slots.Add(new Tuple<DateTime, DateTime>(i, i.AddDays(6)));
}
foreach (var slot in slots)
{
Console.WriteLine("{0}\t{1}", slot.Item1.ToString("dd/MM/yyyy"), slot.Item2.ToString("dd/MM/yyyy"));
}
Console.ReadLine();
}
static DateTime FirstMonday(DateTime date)
{
while (date.DayOfWeek != DayOfWeek.Monday) date = date.AddDays(-1);
return date;
}
static DateTime FirstSunday(DateTime date)
{
while (date.DayOfWeek != DayOfWeek.Sunday) date = date.AddDays(1);
return date;
}
}
This solution allows you to customize your start and end DayOfWeek:
Solution:
public Dictionary<DateTime, DateTime> GetWeeklyDateTimes(DateTime from, DateTime to, DayOfWeek startDay, DayOfWeek endDay)
{
int startEndSpan = 7 - endDay - startDay;
// Subtract days until it falls on our desired start day
from = from.AddDays(startDay - from.DayOfWeek);
// Add days until it falls on our desired end day
to = to.AddDays(to.DayOfWeek - endDay + 2);
Dictionary<DateTime, DateTime> dateTimes = new Dictionary<DateTime, DateTime>();
while (to.Subtract(from).Days > startEndSpan)
{
dateTimes.Add(from, from.AddDays(startEndSpan));
from = from.AddDays(startEndSpan + 1);
}
return dateTimes;
}
Example Usage:
// DateTime(2012, 2, 1) corresponds to Year 2012, Month February, Day 1
Dictionary<DateTime, DateTime> dateTimes = GetWeeklyDateTimes(new DateTime(2012, 2, 1), new DateTime(2012, 2, 29), DayOfWeek.Monday, DayOfWeek.Sunday);
foreach (KeyValuePair<DateTime, DateTime> entry in dateTimes)
{
Trace.WriteLine(entry.Key.ToString() + " " + entry.Value.ToString());
}

Iterate through hours in a day

having a DateTime variable, for example:
DateTime testDate = new DateTime(2011,12,15,00,00,00);
how can I implement a foreach loop for every hour of this day?
Something like:
foreach (int myHour in testDate.Date)
{
}
but in this way does not compile.
It is not a good idea to loop 24, because this will not work on days with 25 or 23 hours (time change, daylight saving...).
Use the AddHour function and a target date.
DateTime testDate = new DateTime(2011, 12, 15, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
while (testDate.Date != endDate.Date)
{
Console.WriteLine(testDate.ToString());
testDate = testDate.AddHours(1);
}
More Information
MSDN - DateTimeKind Enumeration
Use for instead:
DateTime date = new DateTime(2011,12,15);
for(int i = 0; i < 24; i++)
{
DateTime time = date.AddHours(i);
...
}
If you really want to use foreach, you could create an extension method like this:
static class DateTimeExtensions
{
public static IEnumerable<DateTime> GetHours(this DateTime date)
{
date = date.Date; // truncate hours
for(int i = 0; i < 24; i++)
{
yield return date.AddHours(i);
}
}
}
...
DateTime date = new DateTime(2011,12,15);
foreach (DateTime time in date.GetHours())
{
...
}
For those who don't like plain old for loops :) :
DateTime testDate = new DateTime(2011,12,15,00,00,00);
foreach (int hour in Enumerable.Range(0,24)) {
DateTime dateWithHour = testDate.AddHours(hour);
}
foreach loop works in list but here testDate.Date never gives you hour. so in substitution of it use for loop or do while or while loop.
The code below allows you to cycle through the hours of the day but also starting from a specific hour. It could be simpler if you do not need to support starting from an hour offset.
DateTime testDate = new DateTime(2011,12,15,13,00,00);
var hoursLeft = 24 - testDate.Hour;
for (var hour = 1; hour < hoursLeft; hour++)
{
var nextDate = testDate.AddHours(hour);
Console.WriteLine(nextDate);
}
To get the hours in DLS time use this:
DateTime testDate = new DateTime(2017, 03, 26, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
//these dates also contain time!
var start = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).Start;
var end = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).End;
var hoursInDay = new List<DateTime>();
while (testDate.Date != endDate.Date)
{
if (start == testDate)
{
//this day have 23 hours, and should skip this hour.
testDate = testDate.AddHours(1);
continue;
}
hoursInDay.Add(testDate);
if (end == testDate)
{
hoursInDay.Add(testDate); //this day has 25 hours. add this extra hour
}
testDate = testDate.AddHours(1);
}
I'm in Denmark, so when I run this it has only 23 hours.
Iterate over all 24 hours of the day:
DateTime testDate = new DateTime(2011, 12, 15);
for (int i = 0; i < 24; i++)
{
DateTime hour = testDate.Date.AddHours(i);
// Your code here
}
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
for ( var i = today; i <= tomorrow; i = i.AddHours(1))
{
// your code
}
simply do this
DateTime testDate = new DateTime(2011, 12, 15, 10, 00, 00);
for (int i = testDate.Hour; i < 24; i++)
{
//do what ever
}

C# Split Times into Hour Blocks

I am in need of some assistance in getting 2 datetimes to split into the hour intervals between them.
This is working with 'pay' data, so it needs to be very accurate. I need to take clockin and clockout, and split them into hour intervals.
Example:
clockin = 5/25/2011 1:40:56PM
clockout = 5/25/2011 6:22:12PM
I need that to look like:
5/25/2011 1:40:56PM
5/25/2011 2:00:00PM
5/25/2011 3:00:00PM
5/25/2011 4:00:00PM
5/25/2011 5:00:00PM
5/25/2011 6:00:00PM
5/25/2011 6:22:12PM
I then plan to check those times against a 'differential' table to see fi they should have a new paycode. But I'll worry about the paycode later.
Any help splitting out the times? Prefer C#, but I also have access to MSSQL2000 (which is where we pull the original times)
How about something like this?
static IEnumerable<DateTime> GetWorkingHourIntervals(DateTime clockIn, DateTime clockOut)
{
yield return clockIn;
DateTime d = new DateTime(clockIn.Year, clockIn.Month, clockIn.Day, clockIn.Hour, 0, 0, clockIn.Kind).AddHours(1);
while (d < clockOut)
{
yield return d;
d = d.AddHours(1);
}
yield return clockOut;
}
This uses iterator blocks but it could easily be rewritten to return a list instead.
Example use:
static void Main(string[] args)
{
var clockIn = new DateTime(2011, 5, 25, 13, 40, 56);
var clockOut = new DateTime(2011, 5, 25, 18, 22, 12);
var hours = GetWorkingHourIntervals(clockIn, clockOut);
foreach (var h in hours)
Console.WriteLine(h);
Console.ReadLine();
}
Output:
2011-05-25 13:40:56
2011-05-25 14:00:00
2011-05-25 15:00:00
2011-05-25 16:00:00
2011-05-25 17:00:00
2011-05-25 18:00:00
2011-05-25 18:22:12
Update: LukeH was clever enough to suggest that you should also copy the DateTimeKind. This is indeed a smart move if you're planning on converting the datetimes to/from local time later on.
var hours = new List<DateTime>();
hours.Add(clockin);
var next = new DateTime(clockin.Year, clockin.Month, clockin.Day,
clockin.Hour, 0, 0, clockin.Kind);
while ((next = next.AddHours(1)) < clockout)
{
hours.Add(next);
}
hours.Add(clockout);
I think something like this should work:
public IEnumerable<DateTime> GetHourlyBreakdown(DateTime startDate, DateTime endDate)
{
var hours = new List<DateTime>();
hours.Add(startDate);
var currentDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, startDate.Hour, 0, 0).AddHours(1);
while(currentDate < endDate)
{
hours.Add(new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, currentDate.Hour, 0, 0));
currentDate = currentDate.AddHours(1);
}
hours.Add(endDate);
return hours;
}
I would do this:
public static IEnumerable<DateTime> GetIntervals(DateTime clockIn, DateTime clockOut)
{
yield return clockIn;
clockIn = clockIn.AddHours(1).Subtract(clockIn.TimeOfDay).AddHours(clockIn.Hour);
for (DateTime dt = clockIn; dt < clockOut; dt = dt.AddHours(1))
yield return dt;
yield return clockOut;
}
Use it like this:
foreach (DateTime dt in GetIntervals(DateTime.Parse("5/25/2011 1:40:56PM", CultureInfo.InvariantCulture), DateTime.Parse("5/25/2011 6:22:12PM", CultureInfo.InvariantCulture)))
{
Console.WriteLine(dt);
}

Categories

Resources