简体   繁体   中英

Automatically calculate expiry date php

In a site I am creating, I want to store member data and in that data I have a start/join date which is easy to get, but I want to automatically calculate the expiry date which I'm having problems with..

Basically all new members will expire on the last day of February each year, so if I join on say 1st Feb 2013 my expiry will be on 28/02/2014, if I join on 1/03/13 or 20/12/13 my expiry will still be on 28/02/2014. ((I don't mind too much about the 1 day that appears on leap years))

Does anyone know how I can work this out - I know it's probably something obvious but I just cant seem to grasp it! :/

(I'll be doing this in php)

Many thanks in advance, Chris

Assuming that you have (or can get) their registration date in a Unix timestamp format, you could do the following:

function calculateExpiry($reg_date)
{
    $next_year = strtotime('+1 year', $reg_date);
    $feb_days = ((($next_year % 4) == 0) && ((($next_year % 100) != 0) || (($next_year % 400) == 0))) ? 29 : 28;
    return strtotime($feb_days.' February '.$next_year);
}

This will always return the last day of February for the following year in a Unix timestamp, so you can format it how you like. I think this logic is suitable, see the following use cases:

  • Register: 01/01/2013 , Returns: 28/02/2014
  • Register: 09/10/2013 , Returns: 28/02/2014
  • Register: 31/12/2013 , Returns: 28/02/2014
  • Register: 01/01/2014 , Returns: 28/02/2015

This should do the trick too :).

function calculate_expiry( $rawDate ) {

    // Convert data into usable timestamp
    $signupDate = strtotime( $signupDate );
    $cutoffYear = date('Y', $signupDate) + 1;

    // Set the expiry to be the last day of Feb (the first day of March -1)
    $expiryDate = new DateTime();
    $expiryDate->setTimestamp( mktime( 0, 0, 0, 3, 1, $cutoffYear ) );
    $expiryDate->sub( new DateInterval('P1D') );

}

Well, we will get the current signup date by doing...

$signup_date = date("m-d-Y"); // or time()

And then offset it by another year

$expire_date = date("m-d-Y", strtotime("+1 year"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM