Subtract datetime from current date time to get a timer - php

I have a column in a mysql databse that is expriation time of created post.... I have a page that is trying to show how many hours and seconds left until the time reaches the expiration time of each post. For instance I have this in my database:
2013-03-07 13:15:39
This shows when this post expires....
Now I want to be able to go to the page that displays each post and then show the amount of time left (based on the current time) until each posts expires.
2013-03-07 12:15:39
I have been using this so far:
$now = new DateTime(date("h:i:s",time()));
$exp = new DateTime($row['time_expires']);
$diff = $now->diff($exp);
printf('%d hours, %d minutes, %d seconds', $diff->h, $diff->i, $diff->s);
Where $row is fetching the post from the database
It has been working somewhat but seems to have issues sometimes... I have no clue why but it sometimes works great but then when I go check it again the time says 15 hours to expiration when it really should say 2 hours

h in date() is a 12-hour clock, which will create confusion, because DateTime will interpret it as a 24 hour one. A DateTime object will have the current time by default, so just use:
$now = new DateTime();
$exp = new DateTime($row['time_expires']);
$diff = $now->diff($exp);
But Marc B's suggestion of doing it directly in the query is probably a better one.

Related

Calculating consecutive days

when a user logins into his account I want to calculate since how many consecutive days this user has loged in.
For this I store the a timestamp in $loginSince and calculating the consecutive days with this formula:
$consecutiveDays = (int)((time() - $loginSince) / DAY) + 1;
The problem is that this counts by seconds, meaning:
if the user logs in at 17:00 (5pm) and on the next day at 15:00 (3pm) the counter is still 1
if the user logs in at 8:00 (8am) and on the next day at 20:00 (8pm) the counter was resetet (beacause the gap between the two logins is greater than 24h and is again 1
I'd like to get real consectuve days, meaning if a user logs in as the following times:
Day 1: 00:01
Day 2: 23:59
Day 3: 15:00
The counter should say 3, because he loged in at three consectutive days. With my current formular this wont work as the the counter would reset between day 1 and 2.
Can anyone give an advise how to handle this please.
Perhaps use date('z'), as that should just give you the day and not the time?
To post the solution I made. It's based on the idea of Ed Heal to always compare fixed times. I had chosen midnight. After that I build the interval of this to also handle year changes and streaks for more than a year
$loginSince = $this->dailyLoginSince($account);
// Create midnight date of the moment the login-streak started
$loginSinceMidnight = strtotime(date('Y-m-d',$loginSince).' 00:00:00');
// We create the difference between the two dates, both at midnight
$numericDayLoginSince = new DateTime();
$numericDayLoginSince->setTimestamp($loginSinceMidnight);
$numericDayNow = new DateTime();
$timestamp = strtotime('today midnight');
$numericDayNow->setTimestamp($timestamp);
$interval = $numericDayLoginSince->diff($numericDayNow);
$loginSinceDays = $interval->format('%a'); // %a = Number of days
// +1 because it seems to be more thrilling, that we already got one day
// by just logging in for the first time.
return $loginSinceDays + 1;

Time calculation activity in Php

I am working on a web application, in which a web user activity is to be block form half hour before of given time.
I need to calculate time half hour before of given time.
Means if a date and time give like 08/04/2015 16:00:00
now need to calculate time half hour before of the given time i.e. 08/04/2015 15:30:00 during this a web activity is blocked for end user.
Please give me suggestion and sample code in PHP.
you can take this for your refrence,
but you need to modify the code as per your requirements
$start_time = strtotime("2008-12-13 10:42:00"); // get this time while user loggs in
$end_time = strtotime(date('Y-m-d H:i:s'));// this is dynamic time, it changes everytime when the page is reloaded
$difference_in_minutes = round(abs($end_time - $start_time) / 60,2); // this will return the diference between two times in minutes
if($difference_in_minutes >= 30)
{
// do you 30 minutes block stuff here
}
let me know if any further classification needed

How to get time difference between two time in a same days? [duplicate]

This question already has answers here:
Closed 10 years ago.
I'm new to CodeIgniter & PHP.
In my database I store users status in IN time and Out Time. I want to calculate that time means, how much time a user was logged in on a particular day. The user may be logged in more than one time or logged out on a particular day.
How can I calculate the time?
Time format is=04:06:37.
If the user logged in 04:06:37 and logged out 04:09:37, then the time difference is 3 min and 0 sec.
The DateTime::diff() function does what you want.
e.g.
$login = new DateTime('2012-09-04 14:00:00');
$logout = new DateTime('2012-09-04 16:00:00');
$interval = $logout->diff($login);
echo $interval->format('%H hours %i minutes %s seconds');
Convert the times to timestamps using strtotime(), then subtract to most recent time from the original time. For example;
$to_time = strtotime("04:09:37");
$from_time = strtotime("04:06:37");
$time_diff = $to_time - $from_time;
echo gmdate('H:i:s', $time_diff);

Time difference between a Date and current Time?

Assume I have a funny video site that shows funny videos to users. Below every video, I want to have a statement that says "5 seconds ago", "31 minutes ago", "Yesterday", "2 days ago" based on a timestamp of the video and the current time.
The timestamp that I have is in the format: 2011-10-17 07:08:00.
I'm not too good with dates, but I'm guessing that I need to find the difference between the 2 date/time in seconds, then decide if its between 0sec & 60sec to display in seconds, or between 60sec & 3600sec to display in minutes, or between 3600sec & 3600x24sec to display in hours, between 3600x24sec & 3600x24x2sec to display yesterday, and so on... I believe I should be using strtotime() but I cant seem to find the current time as those solutions I found used new date() which does not seem to work!
How can I do this?
Btw, side question, when I insert 2011-10-17, 7:08PM EDT into a MySQL timestamp column, it gets converted to 2011-10-17 07:08:00 which is AM. How can I get it to be stored in the correct AM/PM?
You can use the DateTime functions of php.
$datetime1 = new DateTime('2011-10-17 07:08:00');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
From here on you can use some if-statements to output the time difference in another format (seconds, minutes, hours, month, etc.) depending on the actual time difference! The formats for the output are to find here
You can very easily use the DATEDIFF and TIMEDIFF functions of MySQL. Both together tell you exactly how much time has passed.

How to ensure that one time is always less than another

I've got two times that need to be stored into a database. The time format is hh:mm:ss with NO DATE. These times can be changed by the users on the system. One is a time on and the other is a time off. The time off should always be greater than the time on within a 24 hour cycle.
Here is the part that I'm having trouble with. I don't want to limit the user to selecting times before midnight to keep everything in the same "daily" cycle so I'd like to be able to logically determine if the users' times are simply within a 24 hour time period and then test that the on time is always less.
Can someone help me work through this? There are so many time and date functions that I really don't know which one(s) I need to do this; plus, I'm unclear on how I should test for this.
I'm starting to think that there is no way to test for this without having a date included. Just the times is not enough.
The time is always within a 24 hour cycle, so if the user puts 01:00/03:00 he's on for 2 hours
If he writes 03:00/01:00 he's on for 22 hours.
I dont see the problem.
The OP wrote in a comment:
The user can opt to get a report
delivered in a window of time. The
user may opt to have their reports
delivered in a window from 23:00:00 to
01:00:00 hours. They may decide
tomorrow that that time is no longer
good and change it to 23:0:00 to
05:00:00 or something like that. Am I
missing something??
You have no problem in the time definition part. You may want to play with the code that sends out the report.
// current time
$timeNow = time();
// fetch user time options from database
$timeOn = [from the database];
$timeOff = [from the database];
// convert times to seconds from epoch
$timeOn = strtotime($timeOn);
$timeOff = strtotime($timeOff);
// if database time is in timestamp format,
// only the hour, minutes and second information is needed
$timeOn = mktime(date("H", $timeOn), date("i", $timeOn), date("s", $timeOn));
$timeOff = mktime(date("H", $timeOff), date("i", $timeOff), date("s", $timeOff));
// if time on is higher than time off, time on is of yesterday
if($timeOn > $timeOff){
$timeOn = strtotime("-24 hour", $timeOn);
}
// decide on report sending
if($timeNow >= $timeOn && $timeNow <= $timeOff){
// Send report
} else {
// Do not send report or reschedule the report
}
Any two times in hh:mm:ss format are going to be within a 24 hour time period, as you state. So unless you actually store a date, I am not sure how you can do this.
If I understand correctly, a start time of 23:00:00 and an end time of 04:00:00 should be acceptable to you (this just means 5 hour work shift)? If this is acceptable, then can you give me an example of unacceptable input?
Perhaps you want to check that the end time is within 12 hours of the start time? That should be feasible.

Categories