Loop Through All Months in a Date Range

Loop through all months in a date range?

Try

$start = $month = strtotime('2009-02-01');
$end = strtotime('2011-01-01');
while($month < $end)
{
echo date('F Y', $month), PHP_EOL;
$month = strtotime("+1 month", $month);
}

Mind the note http://php.net/manual/de/datetime.formats.relative.php

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

As of PHP5.3 you can use http://www.php.net/manual/en/class.dateperiod.php

Loop through date range with a monthly step

There are lots of way to do it, but trying to keep it similar to what you have, removing things that are not needed, and using a Dictionary instead:

Sub test()
Dim sDate As String
Dim dict As Object
Dim Cell As Range

Set dict = CreateObject("Scripting.Dictionary")

For Each Cell In Range("F2", Range("F2").End(xlDown))
sDate = Format$(Range("D" & Cell.Row), "mm/yyyy")
If Not dict.Exists(sDate) Then
dict.Add sDate, 1
Debug.Print sDate
End If
Next

Debug.Print "Total: " & dict.Count

End Sub

There are things you can do with the Dictionary afterwards if your Debug.Print is not exactly what you needed.

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).

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().

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.

Loop through months in daterange get first and last date

They go off because of day lights saving time. Just pass in the hour as well when you create the date.

for(let a=0;a<12;a++)
{
let year = new Date().getFullYear()
let firstDay = new Date(Date.UTC(year, a , 1));
let lastDay = new Date(Date.UTC(year, a + 1, 0));
document.body.innerHTML += `<div>${firstDay.toISOString().substring(0, 10)} - ${lastDay.toISOString().substring(0, 10)}</div>`;
}

Working Example

Output

2019-01-01 - 2019-01-31
2019-02-01 - 2019-02-28
2019-03-01 - 2019-03-31
2019-04-01 - 2019-04-30
2019-05-01 - 2019-05-31
2019-06-01 - 2019-06-30
2019-07-01 - 2019-07-31
2019-08-01 - 2019-08-31
2019-09-01 - 2019-09-30
2019-10-01 - 2019-10-31
2019-11-01 - 2019-11-30
2019-12-01 - 2019-12-31

**Update

As per RobG suggestion below. Edited to remove timezone offsets altogether.

easy way to loop over months and years from a given date

Date target = new Date(2011, 4, 1);
while (target < Date.Today) {
// do something with target.Month and target.Year
target = target.AddMonths(1);
}

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
}

Iterate through date range - monthwise

You can use month periods for Series.dt.to_period for groups by months:

months = df['opened_at'].dt.to_period('m')

for month, g in df.groupby(months):
print (g)


Related Topics



Leave a reply



Submit