Most efficient way of playing with dates?
So I've got this unix timestamp from the past which I needed to convert into a date:
$firstDate = date('Y-m-d H:i', 1195958278);
Next I added 90 days:
$expiry = date('Y-m-d H:i', strtotime('+90 day', $firstDate));
This is because each pass is valid for 90 days after the first date. I then proceed by figuring out how many days are left for the pass to expire:
$daysLeft = 365 - (date('z', strtotime(date('Y-m-d H:i'))) - date('z', strtotime($expiryDate)));
I've tested it with a bit of data and it seems to work.
Does anyone see something totally wrong? Or maybe an easier alternative?
||12-13-2007 07:38 PM
I dont use strtotime, unix timestamps are seconds since the unix epoch (1/1/1970), so 90 days from now would be $time + (60*60*24*90), the remainder of days would be time - $original_time / (60/60/24)
Just my preference.
||12-13-2007 07:57 PM
This is how I modified your code to work:
$first = 1195958278;
$last = mktime(0, 0, 0, date("m", $first) , date("d", $first)+90, date("Y", $first));
$today = mktime(0, 0, 0, date("m") , date("d"), date("Y"));
$remaining = floor(($last - $today)/86400);
will be your days left. You may have to switch the floor() function to ceil()... I didn't figure out the real difference in the dates but this script shows 71 days remaining. Tell me if this is wrong and I'll fix it up for you.
||12-13-2007 08:05 PM
As an aside, you don't need to do
date('z', strtotime(date('Y-m-d H:i')))
to get today's day of the year. Simply skip the second argument to use the current time stamp:
Personally, I'd prefer working with the timestamps themselves and only use the date() function for outputting friendly strings. Something like the the following:
;// expiry = starting timestamp + 90 days (in seconds)$iDateExpire
;// Days left = difference between timestamps in seconds (expiry - now)// divided by number of seconds in a day (86,400)// Use floor() to round down to the day.$iDaysLeft
;// Output:// There are 71 days left until 2008-02-23 02:37.printf('There are %d days left until %s.'
, date('Y-m-d H:i'
||12-13-2007 11:40 PM
Originally Posted by Salathe
Personally, I'd prefer working with the timestamps themselves and only use the date() function for outputting friendly strings.
Quoted in agreement.
||12-14-2007 07:46 AM
The most efficient way of working with dates in PHP it's by operating on the date timestamp and just output the formatted one (yes I am agreeing with Salathe) :D
Thanks for everyones input.
Now that I think about it, playing with the timestamp itself seems better.
|All times are GMT. The time now is 10:45 AM.
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0