计算两个日期之间的周末 [英] Count weekends between 2 dates

查看:224
本文介绍了计算两个日期之间的周末的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个价格计算器,周末有特价。为此,我需要知道两个日期之间有多少个周末。

I'm writing a price calculator where weekends have a special price. To do this I need to know how many weekends there are between 2 dates.

请注意,在周末之前,我的意思是如果他们要在星期四至星期二(星期六)和星期日不是2天的周末费率,而是1个周末的单费率。因此,对于周四->周二,这将是一个周末的计数。

Note that by a weekend, I mean if they want to have thursday to tuesday, the saturday and the Sunday are not 2 days with a weekend rate, but 1 weekend with a single rate. Thus for Thursday -> Tuesday, that would be a count of 1 weekend.

对于周六->周六,这将是2个周末的计数,因为第一个星期六是与下一个星期六不同的周末。周日至周日也是如此,无论周末是完整周末还是部分周末,它都在计算周末。只要周末的某些时间或部分处于该日期范围内,就算为1个周末。我能想到的最好的类比是考虑周末持续48小时,而不是持续24小时的2天。

For Saturday -> Saturday that would be a count of 2 weekends, as the first saturday is not the same weekend as the following saturday. The same would also be true of Sunday to Sunday, it is counting weekends, regardless of whether they are full weekends, or partial weekends. As long as some or any portion of the weekend falls within that date range, it counts as 1 weekend. The best analogy I can think of is to consider the weekend a single day that lasts 48 hours, not 2 that last 24.

所以,我怎么确定有多少整个或部分周末是在php中有两个日期之间?

So, how would I determine how many 'whole or partial weekends' there are between 2 dates in php?

推荐答案

我们必须先确定两个周末之间的天数日期。
类似于

We have to start with determining the number of days between the dates. That would be something like

$n = floor((timestamp_end - timestamp_start)/86400);

如果您说Saturday-> Saturday = 2,那么除非我们的开始日是星期六,天数是7的乘积,周末数将为$ n / 7,否则为$ n / 7 + 1。因此,我们可以从这里开始。

If you say that Saturday->Saturday = 2, then unless our start day is a Saturday and the amount of days is a product of 7, the number of weekends will be $n/7, otherwise, $n/7+1. So we could start off with.

$n_weekends = ceil($n/7);

然后

if (date("N", timestamp_start) == 6 && $n%7 == 0 ){
  $n_weekends++;  
}

这篇关于计算两个日期之间的周末的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆