I'm working on a calendar/planner web app and I need to compare the start and end times of events before I store them in my DB. An event can only have a range of one day and between 8am and midnight. The start time always has to take place before the end time.
The post values come from the form in the following format hh:mm:ss (12:14:00) etc.. so I can store them in my database without much hassle. Is there any way I can compare these times?
Thanks a lot!
If those times are in the database, comparison operator of the database would works. For example:
SELECT * FROM table WHERE time < NOW()
In PHP, the easiest way to compare times is to convert them to timestamps, and then to compare timestamps as integers. You can use strtotime to do that conversion.
For example:
$time1 = "08:00:00";
$time2 = "09:00:00";
if (strtotime($time1) > strtotime($time2) ||
strtotime($time1) < strtotime("08:00:00")) {
...
}
If you're running PHP 5.3, you can use the diff() method of DateTime objects to get the difference in between two dates. But it's possible to do with just timestamps too (1 day = 86400 seconds)
Related
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.
What i want is simple, i have timestamp in my mysql database that records date and time data registers. What i want is to calculate the timediff between timestamp and current time then subtract from 3hours to know time remaining in hh:mm:ss format, please someone help out.
You should use the following part in your query:
SELECT TIME_FORMAT(SEC_TO_TIME(AVG(TIMESTAMPDIFF(SECOND, NOW(), column_with_date_to_compare))), '%H:%i')
You must skip the AVG part if you do not want averages but a result per row (or you have only one row to check) (or use GROUP BY [something])
The part 'then subtract from 3hours', I don't understand. You only want to show the records where the time is less than 3 hours? Just use WHERE TIME(record_to_check) > (NOW() - 10800).
If you want to add, calculate or do other things to influence the result, just do so before SEC_TO_TIME, you can do the math (with seconds) there.
I've interpretted your question as how to calculate the time remaining in a 3 hour period starting at a datetime stored in a DB, to be displayed in HH:MM:SS format...
I generally find it easier to manipulate dates / times in php rather than wihtin an SQL query. So my approach would be to:
read strings from the database
convert them into unix timestamps (ie
number of seconds elapsed since a given epoch)
manipulate them mathematically (ie add on 3 hours and subtract the curent time)
lastly convert the result back into a date / time in your chosen
format.
Assuming $start_str has been read from your DB
$start_str = '08-03-2017 11:10:00';
$start_ts = strtotime("$start_str");
$end_ts = $start_ts + (3 * 60 * 60);
$now_ts = strtotime('NOW');
$remaining_ts = $end_ts - $now_ts;
$remaining_str = ($remaining_ts > 0)? sprintf('%02d:%02d:%02d', ($remaining_ts/3600),($remaining_ts/60%60), $remaining_ts%60) : "None, time's up";
echo ($start_str.'|'.$start_ts.'|'.$end_ts.'|'.$now_ts.'|'.$remaining_ts.'|'.$remaining_str);
Examples...
08-03-2017 11:10:00|1488971400|1488982200|1488983863|-1663|None, time's up
08-03-2017 14:30:00|1488983400|1488994200|1488983982|10218|02:50:18
Obviously in reality you're only interested in the last field, but the others show you what you're playing with during the process.
For a while I had been using a raw MySQL NOW() function to record the time/date in my MySQL DB until I realized the host's timezone variable was three hours ahead of PST. I've fixed this using DATE_SUB(NOW(), INTERVAL 3 HOUR), but now I have a ton of timestamps that are three hours ahead, and all future timestamps that are the showing the correct time.
Is there a PHP function to evaluate timestamps recorded before I made the fix so I can offset them when they display in my admin utility?
For example:
if($timestamp < 2012-02-16 21:57:18) {
$timestamp - 3 hours;
}
New Timestamp (offset by 3 hours behind)
$timestamp = date('Y-m-d H:i:s',strtotime($row['timestamp_column_name'])-(3*60*60));
Create a second column in your table (perhaps?) and store the offset time - perhaps call it the admin time OR store the admin time offset from the system's time OR you can set the timezone PHP should use using something like the options mentioned here: PHP timezone not set .
the magical function strtotime does all the work for you. seriously check it out for adding, manipulating and even reading human readable forms of dates. Then the date function is good for formatting it back into any form.
For many input formats, strtotime is the way to go. However, its heuristical approach may lead to surprising results, so if you only want to parse a specific format, use strptime.
Hi All
im trying to build a simple form that the user use it to enter his leave request.
the form contains from time input field and to time input field,and these two filds will contains values in this syntax:
from time: 15:59 pm
to time: 16:59 pm
i have two questions:
1. what is the Datatype that i should use to store p.m and am in the record in mysql database, and not only the time?(i try to use Time,DateTime Date) but these datatypes only stores the time without p.m,a.m
2. what is the best way to calculate the diffrence between these two times?
Thank You
If you are comparing dates/times I find it easiest to work with a timestamp.
There are tons of date functions in PHP if it's just to output the date in the format you want have a look at date functions
The best way to store times in the database is in 24-hour time and use PHP's date function to format the time when you pull it to display it using AM or PM.
To compare two times, I suggest looking at thestrtotime function. This will return the time in UNIX fashion (seconds). You can then compare which time is greater or less than each other, or even perform basic mathematics operations on them (like determining the amount of seconds between each time and then dividing by 60 to determine minutes, etc).
Just store it as a timestamp, you can add pm/am automatically when you output:
print date('G:i a',1294239540); // prints 15:59 pm
and to get the difference in seconds just use strtotime and substract:
print (strtotime('16:59') - strtotime('15:59')); //prints 3600 (1 hour in seconds)
1) This doesn't make any sense - the database stores a representation of an exact instant in time, not an ambiguous 12 hour format with no am/pm. Regardless of how the db is storing it, you can just calculate the am or pm:
<?php
$am_pm = date('a', $timestamp);
?>
or even better, in mysql using your time field:
SELECT DATE_FORMAT(date_field, '%p')
2) For this you can use either php's date_diff, or in mysql:
SELECT DATEDIFF(date_one, date_two)
question 1
stored as time, which use ISO 8601 (hh:mm:ss)
question 2
use timediff, like
select timediff(cast('13:59:29' as time), cast('10:20:00' as time));
>> 03:39:29
To display the AM/PM
select time_format(cast('13:59:29' as time), '%r');
Storing am and pm when you're using 24 format is redundant. Anything between 11:59 and 00:00 is automatically pm. DateTime/timestamp should be more than sufficient to do what you're trying to accomplish. Then you can convert it using strftime back to 12-hr with am/pm.
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.