Iterate Over Days, Starting from X Date Through an End Date

Iterate over days, starting from x date through an end date

You can use ranges :

(Date.new(2012, 01, 01)..Date.new(2012, 01, 30)).each do |date|
# Do stuff with date
end

or (see @awendt answer)

Date.new(2012, 01, 01).upto(Date.new(2012, 01, 30)) do |date|
# Do stuff with date
end

Iterating through a range of dates in Python

Why are there two nested iterations? For me it produces the same list of data with only one iteration:

for single_date in (start_date + timedelta(n) for n in range(day_count)):
print ...

And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.

After all, a linear sequence should only require one iterator, not two.

Update after discussion with John Machin:

Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:

from datetime import date, timedelta

def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)

start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
print(single_date.strftime("%Y-%m-%d"))

NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().

How to iterate through dates from start date to end date?

For a hilariously inefficient way of doing things:

for x in {20141212..20170202}
do
date --date="$x" &> /dev/null && whateverCommand "$x"
done

For a quicker way:

x=0
while :
do
thisDate=`date --date="20141212 $x days" +%Y%m%d`
whateverCommand $thisDate
if [[ $thisDate = 20170202 ]]; then break; fi
((x++))
done

How do I loop through a date range?

Well, you'll need to loop over them one way or the other. I prefer defining a method like this:

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}

Then you can use it like this:

foreach (DateTime day in EachDay(StartDate, EndDate))
// print it or whatever

In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3) in the loop instead of AddDays(1).

Loop through a date range with JavaScript

Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.

var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
daysOfYear.push(new Date(d));
}

Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.

How to loop through range of dates in Swift3 (for each day between x and y, call on a method and pass in that day as a date value)

This should be pretty simple. Just get the difference in days, create a range with it and loop through the number of days, add it to the start date and call your method. Note that I am using noon time as it is recommended for time insensitive calendrical calculations:

extension Date {
var noon: Date {
Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
}


let startOf2020 = DateComponents(calendar: .current, year: 2020, month: 1, day: 1).date!.noon
let now = Date().noon
let days = Calendar.current.dateComponents([.day], from: startOf2020, to: now).day! // 302

(0...days).forEach { n in
let date = Calendar.current.date(byAdding: .day, value: n, to: startOf2020)!
print(date.description(with:.current))
}

How to iterate through range of Dates in Java?

Well, you could do something like this using Java 8's time-API, for this problem specifically java.time.LocalDate (or the equivalent Joda Time classes for Java 7 and older)

for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
...
}

I would thoroughly recommend using java.time (or Joda Time) over the built-in Date/Calendar classes.

What is the most effective way to iterate over a date range in Swift?

If I understand your question correctly, the user will check off some weekdays and provide a duration as a number of days.

Assuming you have the selected weekdays in an array and the duration, you can get the list of matching dates as follows:

// User selected weekdays (1 = Sunday, 7 = Saturday)
var selectedWeekdays = [2, 4, 6] // Example - Mon, Wed, Fri
var duration = 10 // Example - 10 days

let calendar = Calendar.current
var today = Date()
let dateEnding = calendar.date(byAdding: .day, value: duration, to: today)!

var matchingDates = [Date]()
// Finding matching dates at midnight - adjust as needed
let components = DateComponents(hour: 0, minute: 0, second: 0) // midnight
calendar.enumerateDates(startingAfter: today, matching: components, matchingPolicy: .nextTime) { (date, strict, stop) in
if let date = date {
if date <= dateEnding {
let weekDay = calendar.component(.weekday, from: date)
print(date, weekDay)
if selectedWeekdays.contains(weekDay) {
matchingDates.append(date)
}
} else {
stop = true
}
}
}

print("Matching dates = \(matchingDates)")

Is there a way to iterate over specific month or week

There is no time.Date object defined in the standard library. Only time.Time object. There's also no way to range loop them, but looping them manually is quite simple:

// set the starting date (in any way you wish)
start, err := time.Parse("2006-1-2", "2016-4-1")
// handle error

// set d to starting date and keep adding 1 day to it as long as month doesn't change
for d := start; d.Month() == start.Month(); d = d.AddDate(0, 0, 1) {
// do stuff with d
}


Related Topics



Leave a reply



Submit