IT story

날짜를 1 개월 씩 증가

hot-time 2020. 8. 29. 12:42
반응형

날짜를 1 개월 씩 증가


다음 형식의 날짜가 있다고 가정 해 보겠습니다. 2010-12-11 (연-월-일)

PHP를 사용하여 날짜를 한 달씩 늘리고, 필요한 경우 연도를 자동으로 늘리기를 원합니다 (예 : 2012 년 12 월부터 2013 년 1 월까지 증가).

문안 인사.


$time = strtotime("2010.12.11");
$final = date("Y-m-d", strtotime("+1 month", $time));

// Finally you will have the date you're looking for.

월간주기 (더하기 개월, 빼기 1 일)를 제외하고는 유사한 기능이 필요했습니다. 잠시 동안 검색 한 후이 플러그 앤 플레이 솔루션을 만들 수있었습니다.

function add_months($months, DateTime $dateObject) 
    {
        $next = new DateTime($dateObject->format('Y-m-d'));
        $next->modify('last day of +'.$months.' month');

        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }

function endCycle($d1, $months)
    {
        $date = new DateTime($d1);

        // call second function to add the months
        $newDate = $date->add(add_months($months, $date));

        // goes back 1 day from date, remove if you want same day of month
        $newDate->sub(new DateInterval('P1D')); 

        //formats final date to Y-m-d form
        $dateReturned = $newDate->format('Y-m-d'); 

        return $dateReturned;
    }

예:

$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02

사용 DateTime::add.

$start = new DateTime("2010-12-11", new DateTimeZone("UTC"));
$month_later = clone $start;
$month_later->add(new DateInterval("P1M"));

add는 원치 않는 원본 객체를 수정하기 때문에 복제를 사용했습니다 .


strtotime( "+1 month", strtotime( $time ) );

이것은 날짜 함수와 함께 사용할 수있는 타임 스탬프를 반환합니다.


(date('d') > 28) ? date("mdY", strtotime("last day of next month")) : date("mdY", strtotime("+1 month"));

이것은 2 월과 다른 31 일의 달을 보상합니다. 물론 '다음 달 오늘' 상대 날짜 형식 (슬프게도 작동하지 않음, 아래 참조)을 더 정확하게 확인하기 위해 더 많은 검사를 수행 할 수 있으며 DateTime을 사용할 수도 있습니다.

모두 DateInterval('P1M')strtotime("+1 month")본질적으로 맹목적으로 다음 달에 관계없이 일수 31 일 추가됩니다.

  • 2010-01-31 => 3 월 3 일
  • 2012-01-31 => 3 월 2 일 (윤년)

이 방법으로 사용합니다.

 $occDate='2014-01-28';
 $forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=02


/*****************more example****************/
$occDate='2014-12-28';

$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=01

//***********************wrong way**********************************//
$forOdNextMonth= date('m', strtotime("+1 month", $occDate));
  //Output:- $forOdNextMonth=02; //instead of $forOdNextMonth=01;
//******************************************************************//

다음 DateTime::modify과 같이 사용할 수 있습니다 .

$date = new DateTime('2010-12-11');
$date->modify('+1 month');

문서 참조 :

http://php.net/manual/fr/datetime.modify.php

http://php.net/manual/fr/class.datetime.php


먼저 날짜 형식을 12-12-2012와 같이 설정하십시오.

이 기능을 사용하면 제대로 작동합니다.

$date =  date('d-m-Y',strtotime("12-12-2012 +2 Months");

여기서 12-12-2012는 귀하의 날짜이고 +2 개월은 해당 월의 증분입니다.

You also increment of Year, Date

strtotime("12-12-2012 +1 Year");

Ans is 12-12-2013


$date = strtotime("2017-12-11");
$newDate = date("Y-m-d", strtotime("+1 month", $date));

If you want to increment by days you can also do it

$date = strtotime("2017-12-11");
$newDate = date("Y-m-d", strtotime("+5 day", $date));

Thanks Jason, your post was very helpful. I reformatted it and added more comments to help me understand it all. In case that helps anyone, I have posted it here:

function cycle_end_date($cycle_start_date, $months) {
    $cycle_start_date_object = new DateTime($cycle_start_date);

    //Find the date interval that we will need to add to the start date
    $date_interval = find_date_interval($months, $cycle_start_date_object);

    //Add this date interval to the current date (the DateTime class handles remaining complexity like year-ends)
    $cycle_end_date_object = $cycle_start_date_object->add($date_interval);

    //Subtract (sub) 1 day from date
    $cycle_end_date_object->sub(new DateInterval('P1D')); 

    //Format final date to Y-m-d
    $cycle_end_date = $cycle_end_date_object->format('Y-m-d'); 

    return $cycle_end_date;
}

//Find the date interval we need to add to start date to get end date
function find_date_interval($n_months, DateTime $cycle_start_date_object) {
    //Create new datetime object identical to inputted one
    $date_of_last_day_next_month = new DateTime($cycle_start_date_object->format('Y-m-d'));

    //And modify it so it is the date of the last day of the next month
    $date_of_last_day_next_month->modify('last day of +'.$n_months.' month');

    //If the day of inputted date (e.g. 31) is greater than last day of next month (e.g. 28)
    if($cycle_start_date_object->format('d') > $date_of_last_day_next_month->format('d')) {
        //Return a DateInterval object equal to the number of days difference
        return $cycle_start_date_object->diff($date_of_last_day_next_month);
    //Otherwise the date is easy and we can just add a month to it
    } else {
        //Return a DateInterval object equal to a period (P) of 1 month (M)
        return new DateInterval('P'.$n_months.'M');
    }
}

$cycle_start_date = '2014-01-31'; // select date in Y-m-d format
$n_months = 1; // choose how many months you want to move ahead
$cycle_end_date = cycle_end_date($cycle_start_date, $n_months); // output: 2014-07-02

function dayOfWeek($date){
    return DateTime::createFromFormat('Y-m-d', $date)->format('N');
}

Usage examples:

echo dayOfWeek(2016-12-22);
// "4"
echo dayOfWeek(date('Y-m-d'));
// "4"

For anyone looking for an answer to any date format.

echo date_create_from_format('d/m/Y', '15/04/2017')->add(new DateInterval('P1M'))->format('d/m/Y');

Just change the date format.


put a date in input box then click the button get day from date in jquery

$(document).ready( function() {
    $("button").click(function(){   
    var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    var a = new Date();
    $(".result").text(day[a.getDay()]);

    });  
             });

 <?php
              $selectdata ="select fromd,tod  from register where username='$username'";
            $q=mysqli_query($conm,$selectdata);
            $row=mysqli_fetch_array($q);

            $startdate=$row['fromd']; 
            $stdate=date('Y', strtotime($startdate));  

            $endate=$row['tod']; 
            $enddate=date('Y', strtotime($endate));  

            $years = range ($stdate,$enddate);
            echo '<select name="years" class="form-control">';
            echo '<option>SELECT</option>';
            foreach($years as $year)
              {   echo '<option value="'.$year.'"> '.$year.' </option>';  }
                echo '</select>'; ?>

All presented solutions are not working properly.
strtotime() and DateTime::add or DateTime::modify give sometime invalid results.
Examples:
- 31.08.2019 + 1 month gives 01.10.2019 instead 30.09.2019
- 29.02.2020 + 1 year gives 01.03.2021 instead 28.02.2021
(tested on PHP 5.5, PHP 7.3)

Below is my function based on idea posted by Angelo that solves the problem:

// $time - unix time or date in any format accepted by strtotime() e.g. 2020-02-29  
// $days, $months, $years - values to add
// returns new date in format 2021-02-28
function addTime($time, $days, $months, $years)
{
    // Convert unix time to date format
    if (is_numeric($time))
    $time = date('Y-m-d', $time);

    try
    {
        $date_time = new DateTime($time);
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
        exit;
    }

    if ($days)
    $date_time->add(new DateInterval('P'.$days.'D'));

    // Preserve day number
    if ($months or $years)
    $old_day = $date_time->format('d');

    if ($months)
    $date_time->add(new DateInterval('P'.$months.'M'));

    if ($years)
    $date_time->add(new DateInterval('P'.$years.'Y'));

    // Patch for adding months or years    
    if ($months or $years)
    {
        $new_day = $date_time->format("d");

        // The day is changed - set the last day of the previous month
        if ($old_day != $new_day)
        $date_time->sub(new DateInterval('P'.$new_day.'D'));
    }
    // You can chage returned format here
    return $date_time->format('Y-m-d');
}

Usage examples:

echo addTime('2020-02-29', 0, 0, 1); // add 1 year (result: 2021-02-28)
echo addTime('2019-08-31', 0, 1, 0); // add 1 month (result: 2019-09-30)
echo addTime('2019-03-15', 12, 2, 1); // add 12 days, 2 months, 1 year (result: 2019-09-30)

참고URL : https://stackoverflow.com/questions/2870295/increment-date-by-one-month

반응형