我过去使用过许多日期函数,但我需要特定函数的帮助...
是否有一个函数可以让我分配两个未知日期并且系统知道我在这两个日期内的位置?让我解释一下:
我们的每月工资从每月23日到下个月22日。由于收入按小时计算,因此我的老板想知道该月内任何地方的累计工资。例如,工资期从 2012 年 9 月 23 日开始,现在是 29 日,我希望我的查询能够知道我们在当前工资期的位置。
如您所知,几个月过去了,因此我的脚本必须自动知道我们现在处于哪个时期以及该时期内的哪个位置。
我可以对此进行查询,我只需要知道用于分配此数组的日期函数...
任何帮助将不胜感激 - 谢谢
最佳答案
您可以使用 PHP 的 DateTime类可以很容易地做到这一点:-
$periodStart = new DateTime('23rd September');
$now = new DateTime();
$interval = $now->diff($periodStart);
echo "We are {$interval->d} days into the payment period";
输出:
We are 6 days into the payment period.
我更喜欢为这种事情扩展 DateTime 类,所以一切都在同一个地方:-
class MyDateTime extends DateTime
{
public function elapsedDays(DateTime $since = null)
{
if ($since === null) {
$since = new DateTime();
}
$interval = $since->diff($this);
return (int) $interval->d;
}
}
$periodStart = new MyDateTime('23rd September');
echo "We are {$periodStart->elapsedDays()} days into the payment period";
给出相同的输出。
然后,您可以创建周期和间隔并对其进行迭代以汇总总和,如下所示:
$datePeriodStart = new DateTime('23rd September');
$datePeriodEnd = clone $datePeriodStart;
$datePeriodEnd->add(new DateInterval('P1M'));
$dateToday = new DateTime();
$interval1 = $dateToday->diff($datePeriodStart);
$interval2 = $dateToday->diff($datePeriodEnd);
echo "We are {$interval1->d} day(s) into the payment period, {$interval2->d} day(s) left.\n";
$period = new DatePeriod($datePeriodStart, new DateInterval('P1D'), $dateToday);
$days = new IteratorIterator($period);
$totalSalary = 0;
$totalDays = 0;
foreach($days as $day)
{
$salary = get_salary_for_day($day);
$totalSalary += $salary;
$totalDays++;
printf("#%d: %s %s\n", $totalDays, $day->format('Y-m-d'), number_format($salary));
}
printf("Total Salary for %d day(s): %s\n", $totalDays, number_format($totalSalary));
示例输出:
We are 6 day(s) into the payment period, 23 day(s) left.
#1: 2012-09-23 12,500
#2: 2012-09-24 12,500
#3: 2012-09-25 12,500
#4: 2012-09-26 12,500
#5: 2012-09-27 12,500
#6: 2012-09-28 12,500
#7: 2012-09-29 12,500
Total Salary for 7 day(s): 87,500
关于php - 在两个奇数日期选择中查找 NOW(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12653543/