difference between two times in PHP - php

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.

Related

php Compare datetime with hours variation

I have two DateTime, one in database in the same php DateTime format: Y-m-d H:i:s. One is stored in a database and one is retreived.
Unfortunately the second one cannont be compared exactly becazuse there is a certain time (hours) difference. It should be exactly the same time but the difference makes it hard to do a DateTime comparison knowing that comparition must be precise closer to now because of the publish/update date is a matter of a short time (hours, minutes, seconds).
Example: database: 1999-09-06 07:00:00, retrieved: 1999-09-06 09:00:00
I stored the datetime from the distant website a while ago. It worked a few months ago but when I tried to do the same thing today, it failed.
Looks like the webserver has a different timezone as your local time. You can set the TimeZone for the DateTime Class manually. http://php.net/manual/de/datetime.settimezone.php
If the time difference is always the same, you can simple change one value before comparing it. In PHP you can do that quite easily with the strtotime() by subtracting 2 hours. The same can be done in MySQL (or any other DB system) by using SELECT date_column + INTERVAL 2 HOUR: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add

Inserting actual hours (not time) to MySQL

I am trying to insert actual hours not the time itself to MySQL database through form fields. So for example
$time1 = '00:00';
$time2 = '27:20';
$time3 = '00:45';
So I can retrieve the different rows and can calculate on the fly whenever require. Either through search query or even in other area of the system.
When I have tried to do addition of above three times, it is not giving the result the way I am looking for
$total = strtotime($time1) + strtotime($time2) + strtotime($time3);
echo date('H:i:s', $total);
The result
14:16:44
While it should be something like
28:05:00
I have used TIME DATATYPE in MySQL table. I may use as a TEXT but I am also concern about the error happen in user input. Where I do not have to force the user to insert the any particular format but they can either insert as below way
27.20
27:20
or
1.5
1:30
My main concern is to calculate the time, the user input can be on second priority but it would be great if can implement.
So is there anyway, idea or hint to achieve this?
date() expects the timestamp in UNIX format, i.e. seconds since January 1 1970 00:00:00 UTC (which is also the value provided by strtotime)
You're passing it the result of adding a series of amounts of time since 1 January 1970 instead of just adding up hours, so (as far as date is concerned) you're generating a random date and time, and printing only the time (try printing the date of $total and see what you get).
Since your time is stored in the database, one possibility is to let MySQL handle the time calculations itself, e.g.:
SELECT ADDTIME('00:00',ADDTIME('27:20','00:45'))
will result in "28:05:00". You can have your database fields as TIME and operate on them directly through SQL, and do the user input conversions into acceptable TIME values in PHP.
If you're only interested in the hours and minutes, why don't you just store the value as an in integer? Just multiply the hours by 60.
You can handle the conversion in PHP.
Alternatively, you can also easily use two (very small) int fields for this.

Changing date format globally

I am using PHP and mysql and using either Date or DateTime to save dates in mysql database. On site I have been displaying dates the way they are saved in database.
But now I want to show dates EVERYWHERE on site using one format:
April 17 2013
or
April 17 2013 12:20:50
I know I can use date and strtotime functions to display dates in above format. However there are a lot of places where I have date displaying code. So I am looking to automate the process where my current code works and displays dates in above format.
Any idea of how mysql trigger or some php magic could be created that converts all dates run through SELECT query automatically without changing my sql or php code since I have a lot of places in my code and it would be overkill to change code at all places?
For Example:
Date Saved in DB: 2013-04-16 12:41:26
SELECT QUERY: SELECT * FROM myTable
PHP: echo $row->dated; displays 2013-04-16 12:41:26
I want that without changing my php code, dates should be shown in above mentioned format globally on whole site.
Any ideas please how it could be achieved ?
You can directly format in via query using DATE_FORMAT()
SELECT DATE_FORMAT(myDate, '%M %d %Y %h:%i') myDate
FROM TableName
SQLFiddle Demo
and echo in your PHP: $row->myDate
MySQL Trigger doesn't project values and It is only fired during CrUD operations.
I would like to suggest you an alternative approach which i love to use.
You should use the epoch time. An epoch time is basicly the number of second that has passed since 1 January 1970
One if the benefits i love is that it is very easy to calculate
differences in time since you are just dealing with number of
seconds and not a complicated format such as sec min hrs
Another benefit is that it is very easy to store since its a
integer so you can store it in a sql db and have your php code understand it without worrying about the format and things like that.
In php, if you use the time() function, it will return the epoch time.
And if you ever want to display it in a user friendly way. you can use the following code:
$epoch = time();
$dt = new DateTime("$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00
As you can see, the format of the date is very flexible and thus easy to use.
A nice example to find the date 1 week ago:
$epoch = time() - 604800; //604800 seconds = 7 days
$dt = new DateTime("$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00

PHP -Comparing Unix Timestamp To Now

I'm retrieving a unix timestamp from a DB and I want to check if this datetime has passed already.
I tried using an if statement to compare to time() but it always says the time has passed already.
What am I doing wrong?
EDIT: Just some more info..to determine am/pm I'm adding 12 to the hour if its PM before running it through mktime(). (Is this right?)
It's stored in the DB as int not as any datetime types.
Your PHP time could be affected by PHP's timezone. Use date_default_timezone_get() to find out what time zone you're in.
Make sure the timezones in the DB and PHP are the same, use NOW() function to fill the DB column with current timestamp (the column should be of datetime type), then you can get the timestamp using UNIX_TIMESTAMP() MySQL function which compares against PHP's time() just nice.
Alternatively, you can fill the DB column with something like
mysql_query("INSERT INTO your_table (your_date) VALUES (FROM_UNIXTIME(" . time() . "))")
That should work even with timezone discrepancies.
If you are using mktime to create a UNIX timestamp, PHP is using the timezone settings to interpret what you mean by the given parameters. It's possible that you should be using gmmktime. It depends on how the timestamps in the database are being created; I cannot say for sure without seeing more code and having a more detailed explanation.
I generally prefer to simply store all dates as DATETIME types in the UTC (GMT) timezone. It tends to be less confusing.
Just some more info..to determine am/pm I'm adding 12 to the hour if its PM before running it through mktime(). (Is this right?)
12 PM is hour 12.
1 PM is hour 13.
So you don't always add 12. (i.e., 12 Noon is the exception).

Convert time to MySQL Time

I'm trying to store a week schedule (e.g. Monday, 9am-5pm, etc.). I do not have the need to store the dates; I just need to save the following: day, from time, to time.
So, say I have the following time values:
1:20pm
1320
8:00 AM
etc
Assuming that the values are actual valid times, how do I convert these strings into MySQL Time type? And how do I do the reverse? (I'm using PHP.)
Also, how do I query for something like this: find every store that is open on Mondays between 2pm and 3pm? Do I just do something like: WHERE day = 1 AND from_time >= 2pm AND to_time <= 3pm (changing '2pm' and '3pm' to whatever their converted values are, of course)? Or is there some MySQL function better suited for such queries?
MySQL has built in conversion for unix timestamps to a MySQL date:
INSERT INTO table (the_date) VALUES (FROM_UNIXTIME(your_timestamp));
…and the other way around…
SELECT UNIX_TIMESTAMP(the_date) FROM table;
You can use the DAY() and DAYOFWEEK() functions in your WHERE conditionals to convert your MySQL timestamps into the relevant units for you to do your query.
You might need to play around a bit with your schema to determine the best structure to allow you to get the functionality you need here. E.g. it might not make sense to store the day-of-week in a datetime field at all.
MySQL has a TIME data type - it will store values in the hh:mi:ss format, and you can use the TIME_FORMAT function to change the presentation to however you'd like.
Try not to rely on functions applied to the column for comparison - IE:
WHERE TIME_TO_SEC(column) = 123
...because it will render an index, if one exists on the column, useless -- ensuring a table scan (worst performing option).
MySQL understands the ISO 8601 date format, so you have to give time in the form "08:00:00" for 8:00 AM.
You can just use a string with a valid ISO 8601 time in your WHERE clause.
http://en.wikipedia.org/wiki/ISO_8601
http://dev.mysql.com/doc/refman/5.1/en/time.html
http://dev.mysql.com/doc/refman/5.1/en/datetime.html

Categories