FireEnigmaX
FireEnigmaX

Reputation: 577

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

Upvotes: 0

Views: 13547

Answers (3)

adomnom
adomnom

Reputation: 574

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') );

}

Upvotes: 2

BenM
BenM

Reputation: 53208

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

Upvotes: 3

Atticus
Atticus

Reputation: 6720

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"))

Upvotes: -1

Related Questions