What are the pitfalls in the approach to calculate time diff - php

I wish to calculate the difference b/w 2 times in min:sec format . so is my approch correct
date("i:s",(strtotime($User['end_time']) - strtotime($User['start_time'])));

You may get the problems with timezones on some servers.
A bettter way would be using UTC timezone for calculation:
$date = new DateTime('', new DateTimeZone('UTC'));
$date->setTimestamp(strtotime($User['end_time']) - strtotime($User['start_time']));
echo $date->format('i:s');
Another thing, if they are different in exactly 1 hour, the result will be 00:00

strtotime($User['end_time']) - strtotime($User['start_time']) gives you the difference in seconds. Then you pass it to date, so you get the minute and second of the date whose unix timestamp is that.

Related

How to Substract time from datetime

I am using a timezone based script where there is deadline based on timezones. Say for example a deadline is on 7th July at 6PM for a person in IST timezone. The deadline should be 1:30 less than 6pm in Dubai as per their timezone.
I have already calculated the difference between the two timezone difference. I am stuck at deducting that calculated time from the deadline time.
I have saved the timezones in +5:40 +4:00 -4:00 this format instead of using php default ones.
Here's what I use to add and subtract time from a date.
First of all, I get the date from the database and then convert it to a DateTime object.
$date = new DateTime($date);
I use add and a DateInterval to add time. Here's an example to add hours.
$date->add(new DateInterval("PT{$hoursToAdd}H"));
And here's and example to subtract hours intead:
$date->sub(new DateInterval("PT{$hoursToSubstract}H"));
Check this out to know how to work with DateInterval and add/subtract different times: http://php.net/manual/en/class.dateinterval.php
Can you explain a little more specifically what you want to do?
You want to subtract when data already on some var inside your script or you want the SQL query needed ?
If so maybe you can use this answer ---> How to subtract 3 hours from a datetime in MySQL?
The last answer of this post maybe is the one that fit the most what you need :
Assuming you have some timezone issue and know source and destination timezone, you could convert it like so
SELECT
DATE_FORMAT(CONVERT_TZ(x.date_entered, 'UTC', 'Europe/Berlin'), '%Y-%m-%d') AS date
FROM
x
ORDER BY
date ASC;

Codeigniter : Difference Between two time stamps

I am working in codeigniter. I need to take the difference between two time stamps and use this for link expiry in forgot password service.
So far I have tried.
$date= date('Y-m-d H:i'); this will produce something like 2017-03-20 12:02.
Then again in the near future I want to use the same function to get the currunt time. Eventually measure the difference between these two times in minutes.
$past_time = strtotime('2017-03-20 12:02');
$current_time = time();
$difference = $current_time - $past_time;
$difference_minute = $difference/60;
echo 'Difference in minute between two different Time : '.intval($difference_minute);exit;
You can try with this code. This code for give a difference in minutes between two different Time.
The best way to achieve this is to make an extra column like created_at that contains the datetime of link creation in it. When user click on the link get the current date and time and calculate if the difference is acceptable or not as per your policy.
If you are not using database, then add an extra parameter in your link like created_at or valid_upto with encrypted timestamp in it and use it to calculate the time difference and validate it.
You can save your time in unix timestamp using time() function and use simple subtraction for calculate difference b/w two timestamp. it will return number of second b/w two time then convert second to minute dividing by 60.
OR
you can use strtotime() function to convert date into time stamp.

Finding the difference between days

I'm having a table as follows to store future date,
email date
abc#gmail.com 8/10/2014
and I want to do is to find the difference between the above date and the sever date.
I'm using date("m/d/Y") to get the current date.
If date("m/d/Y") = 07/20/2014, then I need the answer as 21.
Please help me find the difference between those days using PHP & MySQL, or suggest a better way to find the difference in days.
You can convert date to timestamp then calculate the days:
(int)(strtotime('8/10/2014')-strtotime('07/20/2014'))/60/60/24
The easiest way would be to store your dates as timestamps, then you could subtract the current timestamp with the one you've saved in a database.
The PHP function time() returns the current timestamp – that is the number of seconds since the 1st of January 1970. You can then format a timestamp $stamp to your liking with date('m/d/Y', $stamp), for example.
Aside from facilitating arithmetic operations with dates, you can display more or less information with timestamps by formatting them with date(), as well as show different formats (July 13, 2014 vs. 07/13/2014). If you save a date as a string, e.g. "8/10/2014", it will be very complicated for you to change the format, and it won't be possible to get the correct time, for example.
Finding how long ago in days a timestamp $stamp was to the current time is very easy:
$now = time();
$days = ($stamp - $now) / (24*3600);
Use round() to get a full number if desired (e.g. 7.2309 would simply become 7).
I'd personally do it using DateTime:
Select your date out into a variable. In this instance We'll call it $DBDate
$DBDateObj = DateTime::createFromFormat('j/m/Y', $DBDate);
$TodayDateObj = new DateTime();
$interval = $TodayDateObj->diff($DBDateObj);
$daysDiff = $interval->days;
In $daysDiff you should now have the difference in days.

Subtract 6 Hours From timestamp Using PHP

I have this code to display a date and time from the database. How would I modify it to subtract 6 hours from the timestamp.
date('m-d g:Ga', strtotime($row['time_stamp']))
UNIX time stamps are seconds since the Epoch. Simply subtract the number of seconds in six hours:
date('m-d g:Ga', strtotime($row['time_stamp'])-21600)
You could alternatively use strtotime again:
date('m-d g:Ga', strtotime('-6 hours', strtotime($row['time_stamp'])))
Since it's in MySQL, you can have MySQL do the calculation for you:
SELECT DATE_FORMAT('...', DATE_SUB(time_stamp, INTERVAL 6 HOUR)) ...
This would save you the overhead of MySQL having to conver its internal representation into a full string, and the overhead of PHP's strtotime() parseing that string just to turn it back into yet another string. While strtotime is magical sometimes, it's definitely not efficient.
$vindate=date('H:i:s', strtotime($row['ms_attend_time'])+19800);
echo $vindate;

Calculating a date

I need to make a timestamp to put into MySQL. The user is submitting a number (of weeks) I need to add that many weeks to today's date. What I am trying to do is calculate an end date of an ad that the user is submitting.
Any suggestions on how to do this? Thanks!
You can use strtotime to add time to a date - it takes a second argument that is the current time if none is passed. You can then pass that created time to the date function to create your timestamp:
$timestamp = date('Y-m-d H:i:s', strtotime('+10 weeks'));
I think DATE_ADD(CURDATE(), INTERVAL 2 WEEK) would add 2 weekss to the current date, for instance
If you want the ad to expire at a certain time of day you can use mktime:
$day = date("d") + ($weeks * 7);
mktime($hour,$minute,$second,$month,$day,$year);
Just to add, some would say that storing the UNIX time as a plain-old int field in the database is the more flexible and portable solution. Furthermore, inserts and updates happen faster because they only involve storing simple integers. It really depends on how much date manipulation you need to do at the database level. I tend to go for portability and do all my date calculations in PHP. To store the current timestamp, I would just insert into an integer column the output of:
strtotime('now');
or
time();
which both return the current (unix) timestamp. Date comparison thereafter can be done by fetching timestamps from the database and performing simple arithmetical operation, as trivial as:
if($tsFromDb > strtotime('+28 days')) {
echo 'it is the future, zombies!';
}
It really depends on what you're using dates for.

Categories