Search code examples
phpdatetimecountdown

How to make the final value of a countdown become new starting value?


I am working on a school project where I am keeping track of a user's tweeting frequency per week. I have working code, but at the end of each 1-week period, I need to manually adjust the new starting tweet total and the date of one week in the future.

How can I automate it so the final tweet count becomes the new starting tweet count, and one week gets added to the ending date? Am I heading in the right direction with the code below, or should I be storing these final tweet total values in a database? Thank you!

// Get current tweet total and calculate current count

$ptTotal = $ptObject->{'statuses_count'};
$ptStart = 572;
$ptCount = ($ptTotal-$ptStart);

// Set end date & convert to EST

$ptdatestr="2017-05-30 12:00:00";
$ptdate=strtotime($ptdatestr)+14400;

// Calculate time remaining

$ptdiff=$ptdate-time();
$ptdays=floor($ptdiff/86400);
$pthours=round(($ptdiff-$ptdays*86400)/3600);

// Re-set start value and add one week to countdown

if ($ptdiff <= 0) {
$ptStart = $ptTotal;
$ptdate = $ptDate + 604800; 
}

Solution

  • I say regardless of how you are automating this code block (see Alejandro's comment), you should move away from using any approach that includes +86400 (or a factor of). Things will go BONK in the night when daylight savings is involved.

    Instead, I recommend that you integrate DateTime objects. They are highly versatile and have specific features that will aid you in your specific project. This is a full list of related functions: http://php.net/manual/en/book.datetime.php

    Implementing Datetime objects and functions will make your project solid and lean. Immerse yourself in the above php manual pages and the comments that follow; and continue to research on StackOverflow.

    More to your specific questions: Yes, I think you are on the right path. Yes, I think I'd store the data in a database.

    Good luck.