PHP中是否有任何函数或方法可以用于确定相应日期的半个月


Is there any function or method in PHP that would be useful in determining the half of the month of the corresponding date?

这个技巧通常在工资系统中使用,在那里你必须确定它是月底(通常是每月的28、31或30天)还是半月(每月的15天)。有什么函数可以很容易地确定它吗?

没有现成的函数,但您可以根据需要创建条件,参见下面的示例:

半月:

if(date('d') == 15){
    echo 'today is Half of the month';
}

月末:

if(date('d') == date('t')){
    echo 'today is end of month'
}

另外,我建议你仔细阅读PHP手册

中的Date Ref

您可以使用DateTime或strtotime来轻松获取当前月的最后一天,例如…

new DateTime('last day of this month');
strtotime('last day of this month'); // alternatively

第一个会给你一个DateTime对象,像这样…

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2015-07-31 05:03:37.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

第二个是整数,表示从纪元1438319031

开始的秒数

也许你可以试试这个:

<?php
public static function get_days_of_month($month, $year, $half = 0) {
    if ($half) {
        $days = intval(trim(cal_days_in_month(CAL_GREGORIAN, $month, $year)));
        $days = floor($days / 2);
    } else {
        $days = intval(trim(cal_days_in_month(CAL_GREGORIAN, $month, $year)));
    }
    return $days;
}