首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列出薪资覆盖日期

列出薪资覆盖日期
EN

Stack Overflow用户
提问于 2021-02-28 00:34:16
回答 1查看 25关注 0票数 0

我希望使用员工的最后薪资日期生成薪资覆盖日期列表。雇员每15天领一次工资。因此,每个月的覆盖范围应该是1号-15号和16号-每月的最后一天。

例如,

代码语言:javascript
复制
$last_salary_date = "2020-12-01";
$date_now = "2021-02-27";

// I should get the following start and end dates:
// 2020-12-01 - 2021-12-15
// 2020-12-16 - 2021-15-31
// 2021-01-01 - 2021-01-15
// 2021-01-16 - 2021-01-31
// 2021-02-01 - 2021-02-15
// 2021-02-16 - 2021-02-28

$last_salary_date = "2020-02-16";
$date_now = "2021-02-27";

// I should get the following start and end dates:
// 2021-02-16 - 2021-02-28

到目前为止,我已经做了这样的事情:

代码语言:javascript
复制
    $start_date = new DateTime("2021-01-16");
    $end_date = new DateTime(date("Y-m-d"));
    $interval = \DateInterval::createFromDateString('1 month');
    $period   = new \DatePeriod($start_date, $interval, $end_date);

    $salary_dates = [];
    foreach ($period as $dt) {
        if (date("Y-m-d") > $dt->format("Y-m-01")) {
            $salary_dates[] = (object) [
                'start_dt' => $dt->format("Y-m-01"),
                'end_dt' => $dt->format("Y-m-15")
            ];
        }
        
        if (date("Y-m-d") > $dt->format("Y-m-15")) {
            $salary_dates[] = (object) [
                'start_dt' => $dt->format("Y-m-16"),
                'end_dt' => $dt->format("Y-m-t")
            ];
        }
    }

    return $salary_dates;

问题是它仍然得到第一个月的1-15号,即使开始应该是16号。我在想一个更好的方法来做到这一点。请帮帮忙

EN

回答 1

Stack Overflow用户

发布于 2021-02-28 01:18:33

以下是修改后的实现。它是为了理解而勾勒出来的,但也可以写成更简短的形式。

代码语言:javascript
复制
<?php

$start_date = new DateTime("2021-02-16");
$end_date = new DateTime("2021-02-27");

$interval = \DateInterval::createFromDateString('1 month');
$period = new \DatePeriod($start_date, $interval, $end_date);

$salary_dates = [];
foreach ($period as $dt) {

    $check_date = function ($date) use ($start_date, $end_date) {
        // check if salary interval is in correct range
        return
            $start_date->format("Y-m-d") <= $date->start_dt
            and $end_date->format("Y-m-d") >= $date->start_dt; // are you sure it shouldn't be ->end_dt ? now it's on order
    };

    // check first two weeks in month
    $salary_date = (object)[
        'start_dt' => $dt->format("Y-m-01"),
        'end_dt' => $dt->format("Y-m-15"),
    ];

    if ($check_date($salary_date)) {
        $salary_dates[] = $salary_date;
    }

    // check second two weeks in month
    $salary_date = (object)[
        'start_dt' => $dt->format("Y-m-16"),
        'end_dt' => $dt->format("Y-m-t")
    ];

    if ($check_date($salary_date)) {
        $salary_dates[] = $salary_date;
    }
}

print_r($salary_dates);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66400970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档