Get the Number of Weeks Between Two Dates

Get the number of weeks between two Dates.

It is pretty easy with joda time:

DateTime dateTime1 = new DateTime(date1);
DateTime dateTime2 = new DateTime(date2);

int weeks = Weeks.weeksBetween(dateTime1, dateTime2).getWeeks();

Count number of including weeks between 2 dates

The simplest way is probably to write a method to get the start of a week. Then you can subtract one date from another, divide the number of days by 7 and add 1 (to make it inclusive).

Personally I'd use Noda Time for all of this, but using DateTime:

// Always uses Monday-to-Sunday weeks
public static DateTime GetStartOfWeek(DateTime input)
{
// Using +6 here leaves Monday as 0, Tuesday as 1 etc.
int dayOfWeek = (((int) input.DayOfWeek) + 6) % 7;
return input.Date.AddDays(-dayOfWeek);
}

public static int GetWeeks(DateTime start, DateTime end)
{
start = GetStartOfWeek(start);
end = GetStartOfWeek(end);
int days = (int) (end - start).TotalDays;
return (days / 7) + 1; // Adding 1 to be inclusive
}

Complete example:

using System;

class Program
{
static void Main (string[] args)
{
ShowWeeks(new DateTime(2016, 9, 17), new DateTime(2016, 9, 26));
ShowWeeks(new DateTime(2016, 9, 17), new DateTime(2016, 9, 25));
ShowWeeks(new DateTime(2016, 9, 19), new DateTime(2016, 9, 26));
ShowWeeks(new DateTime(2016, 9, 12), new DateTime(2016, 9, 25));
}

static void ShowWeeks(DateTime start, DateTime end)
{
int weeks = GetWeeks(start, end);
Console.WriteLine($"{start:d} {end:d} {weeks}");
}

// Always uses Monday-to-Sunday weeks
public static DateTime GetStartOfWeek(DateTime input)
{
// Using +6 here leaves Monday as 0, Tuesday as 1 etc.
int dayOfWeek = (((int) input.DayOfWeek) + 6) % 7;
return input.Date.AddDays(-dayOfWeek);
}

public static int GetWeeks(DateTime start, DateTime end)
{
start = GetStartOfWeek(start);
end = GetStartOfWeek(end);
int days = (int) (end - start).TotalDays;
return (days / 7) + 1; // Adding 1 to be inclusive
}
}

Output (in my UK locale):

17/09/2016 26/09/2016 3
17/09/2016 25/09/2016 2
19/09/2016 26/09/2016 2
12/09/2016 25/09/2016 2

PHP - calculating the number of weeks between two dates

The dates you pass to strtotime need to be enclosed in quotes. And the correct answer is indeed 3, as there are 3 weeks, 6 days, 23 hours and 59 minutes between the two times. Try this:

$HowManyWeeks = date( 'W', strtotime( '2019-04-21 23:59:00' ) ) - date( 'W', strtotime( '2019-03-25 00:00:00' ) );
echo $HowManyWeeks;

As has been pointed out, this will only work when the weeks are in the same year. It's easier to use DateTime objects as in @MiroslavGlamuzina answer or you can simply divide the strtotime difference by 604800 (seconds in a week); you can then take the floor or ceil if required to convert to an integer value:

$HowManyWeeks = (strtotime( '2019-04-21 23:59:00' ) - strtotime( '2019-03-25 00:00:00' )) / 604800;
echo $HowManyWeeks;

Output:

3.9939484126984

Demo on 3v4l.org

Most efficient way to count number of weeks between two datetimes

Get the number of days and divide by 7.

int weeks = (date1 - date2).TotalDays / 7;

You may well have a remainder of up to 6 days that will not be included in the number of weeks.

How create field weeks in between two dates

Method 1: Using list comprehension, dt.period & getattr

provided by Jon Clements in comments

This method will work when years change between the compared dates:

cw['weeks_diff'] = (
[getattr(el, 'n', 0)
for el in cw['lead_date'].dt.to_period('W') - cw['Received_date'].dt.to_period('W')]
)

Method 2: using weeknumbers with dt.strftime('%W')

We can use pd.to_datetime to convert your dates to datetime. Then we use the dt.strftime accessor to get the weeknumbers with %W.

Finally we substract both weeknumbers:

weeks = (cw[['lead_date', 'Received_date']]
.apply(lambda x: pd.to_datetime(x).dt.strftime('%W'))
.replace('NaT', 0)
.astype(int)
)

cw['weeks_diff'] = weeks['lead_date'] - weeks['Received_date']

lead_date Received_date weeks_diff
0 2019-12-28 2019-12-15 2
1 2019-12-23 2019-12-21 1

How to calculate the amount of weeks between two week pickers

there are 52 weeks + 1 day in a year and 52 weeks + 2 days in a leap year. So your suggestion amountOfWeeks += yearDiff * 52; does not seem accurate. The below function converts the start and end year and weeks into miliseconds, subract and convert back into weeks. It should work with leap years. I haven't tested it though.

function compareWeeks(startYear, startWeek, endYear, endWeek) {

const start =
new Date(startYear, 0).getTime() + startWeek * 7 * 24 * 60 * 60 * 1000

const end =
new Date(endYear, 0).getTime() + endWeek * 7 * 24 * 60 * 60 * 1000

const diff = Math.abs(end - start)
const diffWeeks = diff / 1000 / 60 / 60 / 24 / 7
return diffWeeks
}

Update for ISO-week-numbering year (your use case):

According to the wikipedia, an ISO Year has either 52 or 53(ISO Leap Year) weeks. 53 when it starts or ends with Thirsday else 52. Checkout the below code:

function weeksInBetween(startYear, startWeek, endYear, endWeek) {
let diff = 0
for (let i = startYear; i < endYear; i++) {
const has53Weeks = isISOLeapYear(i)
if (has53Weeks) {
diff += 53
} else {
diff += 52
}
}

return (diff += endWeek - --startWeek)
/*
the '--startWeek' makes sure the starting week
is not subtracted from the result, because you
want the result to be inclusive'

*/
}

function isISOLeapYear(year) {
const startsWithThursday =
new Date(year, 0, 1).toString().split(' ')[0] === 'Thu'
const endsWithThursday =
new Date(year, 11, 31).toString().split(' ')[0] === 'Thu'

if (startsWithThursday || endsWithThursday) {
return true
}

return false
}

console.log(
weeksInBetween(2020, 1, 2021, 52), // 105
weeksInBetween(2009, 1, 2010, 52), // 105
weeksInBetween(2021, 1, 2021, 52), // 52
weeksInBetween(2021, 1, 2022, 52), // 104
weeksInBetween(2021, 1, 2021, 1) // 1
)



Related Topics



Leave a reply



Submit