如果我有开始日期(比方说2009-02-01)和结束日期(比方说2010-01-01),我该如何创建一个循环来遍历范围内的所有日期(月份)?
我创建了一个函数,它返回一个包含每个月的数组,从提供的碳日期开始到当前日期结束.
虽然该功能正在做它应该做的事情,但它看起来很可怕.很明显,我的编程技巧还不是他们应该做的.当然必须有更好的方法来实现我想要的.
我的代码看起来像这样:
class DateUtilities {
protected $months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
public function getMonthListFromDate(Carbon $date)
{
$monthArray = array();
$today = Carbon::today();
$currentYear = $today->copy()->format('Y');
$currentMonth = strtolower($today->copy()->format('F'));
$startYear = $date->copy()->format('Y');
$startMonth = strtolower($date->copy()->format('F'));
for($i = $startYear; $i <= $currentYear; $i ++) {
foreach($this->months as $monthIndex => $month) {
if (($monthIndex >= array_search($startMonth, $this->months) && $i == $startYear) ||
($monthIndex <= array_search($currentMonth, $this->months) && $i == $currentYear) ||
($i != …Run Code Online (Sandbox Code Playgroud) 这个问题似乎与大约一个月的旧问题相似,但我有一个特殊问题。我不是要计算两个日期之间的月份数,而是要计算两个日期中包含的月份数。我解释。我有 2 个日期:
$begin = new DateTime( '2014-07-20' );
$end = new DateTime( '2014-10-10' );
Run Code Online (Sandbox Code Playgroud)
在这两个日期之间,我有 4 个月:七月、八月、九月、十月。但是使用我正在使用的脚本,我无法找到包含 4 个月但只有 3 个月的脚本。这是脚本:
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
$counter = 1;
foreach($period as $dt) {
echo $dt->format( 'm' );
$counter++;
}
echo $counter;
Run Code Online (Sandbox Code Playgroud)
如何循环计算所有这 4 个月?
我创建了一个用户需要填写的表单.根据年龄答案,我需要列出当年和出生年份之间的所有年份.我能够弄清楚如何将年龄数转换为实际年份:
function birthday_year($years) {
return date('Y', strtotime($years . ' years ago'));
}
$byear = birthday_year($age);
echo $byear;
Run Code Online (Sandbox Code Playgroud)
我很难在出生年份和当年之间列出所有年份.任何指导将不胜感激.我能够找到列出几个月的其他代码示例,但是当我尝试将代码操作多年时,它根本不起作用.只有我用PHP的第3周,所以它对我来说仍然很新.谢谢!
我有2个约会。我想获得所有月份的总天数。
我怎样才能在 PHP 中做到这一点?
例如
$date1 = '2013-11-13'; // yy-mm-dd format
$date2 = '2014-02-14';
Run Code Online (Sandbox Code Playgroud)
输出
Months Total Days
-----------------------
11-2013 30
12-2013 31
01-2014 31
02-2014 28
Run Code Online (Sandbox Code Playgroud)