php方式获取每个月的15日期

时间:2016-04-13 16:21:07

标签: php datetime

我试图根据用户提供的输入输出下个月的第15天。

例如:

  

04/02/2016 - 用户输入
  2016年5月15日 - 计算后输出

这是我的代码,我正在尝试:

// this value is already coverted in strtotime.
$today = $loan_data['loan_applied_date'];
$numOfDays = date('t', $today);
$base = strtotime('+'.$numOfDays.' days', strtotime(date('m/01/Y', $today)));
$day15 = date('m/01/Y', $base);
$time = strtotime($day15);

通过运行上面的代码我得到了第一天。我如何获得第15名?

示例场景:

  

假设订阅已于2016年4月4日注册,因此他们的下一个付款日期将是下个月的15日或2016年5月15日。

3 个答案:

答案 0 :(得分:1)

只需使用DateTime

// Your description says that $loan_date['loan_applied_date'] is
// "already coverted in strtotime", so I assume a UNIX timestamp ...
DateTime::createFromFormat('U', $loan_date['loan_applied_date'])

    // When you import a UNIX timestamp into DateTime, it assumes UTC,
    // so we need to set your timezone back to whatever it is
    ->setTimezone(new DateTimeZone(date_default_timezone_get()))

    // Add 1 month
    ->modify('+1 month')

    // Hard-code the 15th day
    ->format('15/m/Y');

答案 1 :(得分:0)

解决方案非常简单,使用PHP可以利用灵活的mktime功能,如下所示:

<?php

$today = strtotime("now");  //GRAB THE DATE - YOU WOULD WANT TO REPLACE THIS WITH YOUR VALUE

$year = date("Y", $today);  //GET MONTH AND YEAR VALUES
$month = date("m", $today);

$month++;                   //INCREMENT MONTH

echo date("d/m/Y", mktime(0, 0, 0, $month, 15, $year)); //OUTPUT WITH MKTIME

?>

答案 2 :(得分:0)

我做了类似于定期付款的事情,此代码每15日收取一次费用:

//ini_set("date.timezone", "America/New_York"); //uncomment for test timezone
function getLastDay($date=false){
    return $date?date("t", strtotime($date)):date("t", strtotime(0));
}
function monthDayMatch($data = array('startDay'=>1,'day'=>1,'lastDayMonth','startMonth'=>1,'month'=>1,'frecuency'=>1)){
    if(($data['startMonth']%$data['frecuency'] == $data['month']%$data['frecuency']) && ($data['startDay'] == $data['day'] || $data['startDay'] > $data['lastDayMonth'])){
        return true;
    }
    return false;
}

$date = '04/02/2016';
$date = explode('/',$date);
$customer_date=array('month'=>$date[0],'day'=>$date[1],'year'=>$date[2],'all'=>implode('/',$date));  

$resp = monthDayMatch(array(
    'startMonth'=> $customer_date['month'], //initial customer month
    'month'     => date('m'),               //current month
    'frecuency' => 1,                       //recurring once a month
    'startDay'  => date('d'),               //current day day
    'day'       => 15,                      //day to validate
    'lastDayMonth'=>getLastDay($customer_date['all'])
));

//every 15th is true
if($resp){
    echo 'payment charge';
}else{
    echo 'no payment';
}