Inserting actual hours (not time) to MySQL - php

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.

Related

redis timeseries data and timezones

I'm trying to implement a timeseries db to store simple counters using redis (and php, but the language shouldn't be relevant i think). So I've implemented my redis keys as follows (simplified):
someprefix:YYYY-MM-DD:somecounter
Now when i want to get a range of data for a specific interval i just get all keys for the specific range and that's all working fine. (YYYY-MM-DD is the date as UTC)
Now i want to implement the ability to get data according to some timezone X.
My question is: is there any way this key schema can be used for that with any degree of accuracy?
I'm guessing not, since there's no time information at all so i'll also have to add at least the hours and minutes to the key so timezone conversion works correctly. I also probably should save the information in smaller time intervals otherwise when converting timezones there are cases where I would end up getting all data for a different day when the timezone difference shouldn't be more than 13h therefore giving me wrong results, am I right?
Would it be more appropriate to just use unix timestamps instead of the formatted date on the redis keys? For example, if I later on decide to store data with smaller precision, say per hour or per each 10 minutes, what would be a more flexible key format?
Hope I was able to explain my issue correctly, but please feel free to ask for any clarifications.
Thanks
Its always good to go with epoch (UNIX timestamp) when you have to deal with timezone.
I would suggest bucking timestamps to frame the Keys. For example an event happened at timestamp 1409800502515(Thu, 04 Sep 2014 03:15:02 GMT), you could bucket it at Hour level or Day level like this
Hour bucket = 1409800502515 - (1409800502515 % (60 * 60)) = 1409800500000
Day bucket = 1409800502515 - (1409800502515 % (24 * 60 * 60)) = 1409800464000
and frame keys like
someprefix:1409800500000:somecounter OR
someprefix:1409800464000:somecounter
For example for calculating the page views per hour, find the appropriate hourly bucket and increment the counter
mypage.html:1409800464000:page_views INCR 10
Firstly, I'm not sure how you're doing "get all keys for the specific range and that's all working fine" but if you're using KEYS someprefix:* note that this is not a recommended practice for production. Consider using the SCAN command that's available from v2.8 instead.
Secondly, you could consider using an ordered set for counting. So, following your convention, you'll have a key called someprefix:somecounter that you'll be ZADDing to members with the epoch as their score. Use the epoch and the counter's reading as a unique member name (e.g. '1409800500000:1` where 1409800500000 is the epoch and 1 is the counter's value).
Note that you can measure time resolutions from years to microseconds - it all depends on how much div you apply to the original epoch before setting the score.

Extracting server time with PHP and storing in MySQL - Unix time stamp OK?

All,
I'm trying to decide how to deal with time in a project which relies on (server) time intervals (in short, some content is available after user completed a specific action at least n hours before). Right now, it seems like the easiest option would be to extract the Unix time stamp with time() and store it as is in MySQL.
Any reason why this is not a good idea? Any gotcha I need to be aware of? Performance impact?
Timestamps are fine. Don't divide them, it's unneeded calculation. If you plan to query (per object) about a timeout more often than update it then you would be better off storing the expiration time instead of the current (so calculating delta only once). Beware about DATETIME columns: they don't regard timezone setting, while your PHP does... so if you happen to have different timezone settings on different requests, then you're out of luck. Timestamps are absolute, and they also account for manace like daylight-savings times, where 3:01 is 2 minutes after 1:59...
Seems fine to me. Though you should probably store it as a DATETIME and use DateTime objects, rather than UNIX timestamps and time().
$time = new DateTime;
echo $time->format("Y-m-d H:i:s"); //Outputs current time, example: 2012-10-13 22:58:34
Actually, this is the best idea. The function time() give you the number of seconds from January 1th, 1970 00:00:00. There's no performance impact because it's only an integer. In MySQL, create a field like that INT, 10, Unsigned.
Time will give you performance on the SELECT and the WHERE. See http://gpshumano.blogs.dri.pt/2009/07/06/mysql-datetime-vs-timestamp-vs-int-performance-and-benchmarking-with-myisam/
The only problem you have is : time is limited to year 2038... but by the time 2038 come, the internal computer clock bytes will be larger ... hope so.
The other thing you may want to worrie about the DATETIME is : PHP time() run under UTC, while DATETIME depend on the timezone...
Stats when you do INSERT with 10000000 rows.
Stats when you SELECT / WHERE with indexes :

How do I evaluate a timestamp in PHP?

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.

difference between two times in 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.

Adding values to a Timestamp

I am trying to create a script for quiz. I have stored current timestamp in MySQL DB as quiz start time, and want to check after each quiz how much time is left.
I have the idea that I will add 30 mins to saved time stamp and subtract this value from current time. That will be the time left. But I don't know the exact way of doing this.
My time stamp is saved in DB in format 2010-08-24 20:08:59. Any one have the idea.
Please let me know if someone have done it, or know how to get it.
Adding 30 mins to time stamp and showing the user how much time is left.
I am using the now() function to store the timestamp in DB.
Thanks
I would personally store the output of PHP time() in the database.
If you a human readable format from this value, you could use date('Y-m-d H:i:s', $fromdatabase);.
You want to store an actual UNIX timestamp in the database, not a string in that format.
You may or may not be doing this already, it depends on the type of column you're using. For MySQL, you should be using TIMESTAMP, which allows you to retrieve the timestamp with
SELECT UNIX_TIMESTAMP(column_name) ...
To store the current time + 30 minutes, all you have to do is:
INSERT INTO table (column_name) VALUES(UNIX_TIMESTAMP() + 1800)
You can know if the time has expired by comparing time() against the value of the column.

Categories