How to store users timezone in mysql? [duplicate] - php

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Datatype/structure to store timezones in MySQL
I'll be storing only UTC times in my database, and want to convert the timestamps to a user's local time using PHP.
My question is, what is the best way to store the users timezone in the database?
IE: -400, -4, -4:00
With that said, I know how to do the math manually:
$utc_time = strtotime("2011-10-02 23:00:00");
$my_time = $utc_time - 14400;
echo date($timeformat, $mytime);
My problem is, with the user's timezone being pulled from the database, I don't know whether I'll be adding or subtracting seconds. That's where I run into the problem of trying to figure out how to save the timezone so that I can calculate the offset.
I can save the timezone as "-14400", but using the above example, I can't just combine the two strings to do the math for me using the - sign:
$my_time = $utc_time.$timezone;
So... how do I save the timezone properly to get the math done?

The timezone in one location isn't always the same - for example, the UK is BST (GMT + 1) between March and October. Use one of the timezones supported by PHP:
http://php.net/manual/en/timezones.php
If you do go ahead using numbers, either store them as hours or minutes. Store timezones west of UTC/GMT as negative numbers. For example, the US East Coast would be -5 (hours) or -300 (minutes) - assuming it's 5 hours behind.
Then, add this to the timestamp - the negative or positive will handle the rest.
// for 5 hours behind when stored as hours (-5)
$now = time() + ($offset * 60 * 60);
// for 5 hours behind when stored as minutes (-300)
$now = time() + ($offset * 60);

timezone string would be better than the offset or difference in hours
because some timezones are subject of changes
http://www.php.net/manual/en/class.datetime.php
http://www.php.net/manual/en/class.datetimezone.php
for date/time math:
http://www.php.net/manual/en/class.dateinterval.php
http://www.php.net/manual/en/class.dateperiod.php
stop using php functions, oop classes are much better!

Rather than storing it as a string, store it as a number? Then you can simply add that number to the timestamp. (The number can be negative for timezones which would subtract.)

Related

How to get time difference between current date time and timestamp value in HH:MM:SS

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.

Converting Epoch time to an H:mm timestamp in PHP

This seems like there should be a very easy solution, however everything I'm trying is either giving me an error or the wrong result.
I'm pulling data from a MySQL table and the time is stored in the Epoch format in the database. When I make the query on the website it's showing: 3672 (the same number shown in the database). I've tried using the date() function, a number of different str* functions, different arithmetic operations, however nothing is giving me the actual time, which should be showing as: '1:02'.
I'm not trying to pull the date, actual time, etc. I'm just trying to convert an Epoch time string to a traditional 'H:mm' format, because these are for durations, not timestamps.
Any help would be greatly appreciated!
As others already noticed, this is not really any standard epoch time but simply number of seconds since midnight.
Looking at your example, you only need hours and minutes (rounded up). This will give you those:
$h = (int)($number / 3600);
$m = ceil(($number - $h * 3600) / 60);
$result = sprintf('%d:%02d', $h, $m);
Dividing number by 3600 (60 for seconds * 60 for minutes) will give you number of hours. Using your example of 3672 this will give you 1.
To get minutes you just remove hours to get seconds (72) and then divide that by 60 to get minutes (1 minutes and 12 seconds). Since your example specifies 1:02 is result, you can simply take next upper integer (2).
At end result is 1:02, as you specified.

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.

What are the pitfalls in the approach to calculate time diff

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.

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.

Categories