CodeIgniter local timezone to GMT - php

i need help with multi timezone website in codeigniter.
config.php:
$config['time_reference'] = 'gmt';
date_default_timezone_set('UTC');
now when user want to see event(website is for events) it shows dates to his timezone with gmt_to_local() function, this works fine..
Now problem is when user want to add new event, he picks date and time, now it gets converted to timestamp:
strtotime($event_date);
And problem is that he picks date and time for event on his timezone, now i need to convert it to gmt, and save to db.
Example, if user is in UP2(+2:00) and he set 12-25-2012 22:30:00 it will be converted to timestamp and saved in db, but it is incorrect, it should subtract 2:00 and save that timestamp to db as timestamp of 12-25-2012 20:30:00 (this is converted to gmt)
Hope that you will understand.
Any solution for this?
Thanks.

In your event form, you should send to the server a hidden input witch will contain client's timezone offset. You can get it via Javascript's Date.getTimezoneOffset() method (it gives you offset in minutes between UTC and users's local time).
If you can't do that, you can save user's local timezone into db or ask it in your event form.
Then, in your INSERT or UPDATE query, you can use DATE_ADD('2012-12-13 19:41:00', [user offset] MINUTE) to convert timestamp. You can also do it in php, or client-side when submitting form...
For example in PHP :
strtotime($event_date);
gives you the date's Unix timestamp (so, in seconds). To convert it into another timezone, according you get the offset in minutes with javascript method, you can do :
$dbTimestamp = strtotime($event_date) + $_POST['offsetInMinutes']/60;
If you get the offset in this form : '+2:00' or '-6:00', you can get offset in hours using a regular expression :
preg_match('/(.*)\:00/', '+2:00', $match)
will set '+2' into $match[1]

Related

Vuejs fix date from date received from php server

I have a datetime object received from server in the following format:
{"date":"2021-05-11 13:02:01.273000","timezone_type":3,"timezone":"UTC"}
I'm having trouble to get the correct date corresponding to the user browser how can I parse this date into a js date object with the right time zone calculations. I used to take only the date disregarding the time zone and it turned out to be wrong to the user
Try using toLocaleString method and specify the timeZone:
x = JSON.parse(`{"date":"2021-05-11 13:02:01.273000","timezone_type":3,"timezone":"UTC"}`);
new Date(x.date).toLocaleString("en-US", {timeZone: x.timezone})

PHP UNIX Timestamp not iterating to the same value

I am facing a problem with unix timestamps, php and mysql and would be great if somebody could explain to me where I am going wrong or if I am not then why I am getting the figures that I am getting.
When I use jquery datepicker to pass the date in year-month-date format to php the hour and minutes have been set by default of 23:00:00 in the timestamp even though I am not passing this infromation in the request. So my question is where is this phantom 23:00:00 appearing from?
Workflow:
Using datepicker: datepicker -> php -> mysql = TIMESTAMP which has time set at 23:00:00.
Without using datepicker: php->mysql = TIMESTAMP with the correct hour and minutes.
Thanks for reading.
EDIT: PHP code as requested:
PHP code:
$setdatealpha = $_POST['datepickeralpha'];
$setdatealpha = strtotime($setdatealpha);
// With this, I am inserting into MySQL like so:
$sql = "INSERT INTO TABLE (DATE_FIELD) VALUES (?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s',$setdatealpha);
$stmt->execute();
Now when I read the entered information back and convert it to date time format via date('Y-m-d',timestamp), the date entry correct and the time entry has the 23:00:00 value.
This does not occur if I do a standard converstion via strtotime (date);
Based off of the information currently available, I would suggest that you make sure each timestamp is in UTC. I always run into timezone issues.
For PHP, like: $current_timestamp = strtotime($date." UTC");
For jQuery datepicker I found this stackoverflow thread: How to obtain utc time in jQuery datetimepicker
Most likely, time zone.
First of all, let's clarify the context. strtotime() produces a Unix timestamp, which you apparently feed DATE_FIELD with. If that works, it means that the column is an INTEGER. In the case, you're doing something afterwards to display the date and you haven't shared that part—also, MySQL is innocent here because it doesn't even know what DATE_FIELD is meant to be date.
While strtotime() can be fed with a raw date, it needs to generate time as well. It can't do it unless it knows the time zone. Additionally, when you have an integer variable with a Unix timestamp and you want to display it as proper date you also need to know the time zone.
In both cases, if you don't provide it PHP will use a default value:
var_dump(date_default_timezone_get());
So you'll possibly want to set a known one with e.g. date_default_timezone_set(). However, your users may have a different time zone than you so yours would be meaningless to them. Since you prompt the user for a raw date (without time) it's possible that time is actually not relevant to the question. In such case, you may want to:
Make DATE_FIELD of DATE type.
Avoid strtotime() and similar stuff. You may want to use checkdate() instead.

Render date from date field in correct timezone?

Im have a field with date time type. I see in database is always saved other timezone than my default.
When node content is rendered, date looks fine, but when i trying to get node from code i cant render date in correct timezone.
$node->field_customtime->getValue()
I have array of values with standard timezone, when i dump value, the time is wrong.
So i was trying to do it like that:
$value = $node->field_customtime->getValue();
$value = $value[0]['value'];
$date = new \DateTime($value);
$date = $date->getTimestamp();
echo \Drupal::service('date.formatter')->format($date);
And there is still raw date from database (wrong).
I dont know how to correct display date from custom date field. I see in the form correct date (i.e. 11:00 european time) but in database is 10:00. On node page is correct 11:00 so drupal convert it somehow, but how??
I will assume you are using MySQL?
If so then unless you are saving a timestamp the timezone does not matter. It should be saved exactly how you sent it.
If it is a timestamp then the date is automatically converted into UTC for storage and then converted back into whatever timezone you have set in the mysql configuration.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
What you need to check first is how you are saving the date. Are you storing a timestamp?
If not you need to check how the data is saved and see if anything is happening to the date before inserted into the database.
Unfortunately I do not know much about Drupal but after a quick google I have found out that Drupal 7 happens to have a few ways of handling the datetime. It is quite possible that this may apply for Drupal 8 and you simply need to adjust a configuration.
https://drupal.stackexchange.com/questions/3613/the-differences-between-date-time-zone-handling

Formatting MySQL / Server timestamp with php?

I have a created a timestamp in MySQL that changes when an account is updated by a users, and this timestamp is echoed on the page. However it is displaying the server time rather than my local time. I can't set the timezone in MySQL, I tried. What is another way to change this, and how can it be implemented?
The problem with timestamp datatype is that
MySQL converts TIMESTAMP values from the current time zone to UTC for
storage, and back from UTC to the current time zone for retrieval.
(This does not occur for other types such as DATETIME.) By default,
the current time zone for each connection is the server's time. The
time zone can be set on a per-connection basis. As long as the time
zone setting remains constant, you get back the same value you store.
If you store a TIMESTAMP value, and then change the time zone and
retrieve the value, the retrieved value is different from the value
you stored.
So, it does not really matter what your timezone setting in php is, you need to set either mysql's timezone on a session basis using
SET time_zone = timezone
command, or you need to store the timezone of the client along with the timestamp and adjus the value based on the stored timezone. I would use the latter approach, since a client technically can change timezones and if the client access the timestamp data from a different timezone, then different data will be returned by mysql.
When echoing from a database add in some "filters" seemed to do the trick
<?php echo $row['field name']; strtotime(date("Y-m-d", 1310571061)); ?>
Without the above code it displayed the timestamp as: 2016-02-09 00:00:00
With the above code it displays thus: Tuesday, February 09, 2016

How to deal with timezones between server and client?

I'm developing a website where I have to deal with different possible timezones from the users. This becomes a great problem since the website hosts time-delicate events like auctions.
All dates/times on the server are in UTC. Database stores everything in UTC timestamps. PHP default timezone is set to UTC too (date_default_timezone_set('UTC');).
Now, my problem is how I should interact with the users, whether I'm only showing a date or, more important, I'm reading a date/time from user input.
A concrete example:
An auction has a deadline, which I store in database as UTC.
When I view the auction on the website, a javascript timer uses a Date object to calculate the remaining time. It automatically converts the timezone to GMT+0100 (my local timezone). So if the deadline is '2013-08-08 10:46:08' (UTC), the javascript date object will return Aug 08 2013 11:26:15 GMT+0100 (GMT Standard Time).
If the current time is greater than 11:46:08 then the timer says that the remaining time is 00:00 (which is correct).
But if I try to insert a bid, the server accepts since the condition on the MySQL INSERT evaluates to true:
INSERT INTO Bids ... WHERE ... AND auction_deadline > NOW() ...
( because auction_deadline = '2013-08-08 10:46:08' and NOW() = '2013-08-08 10:26:50')
All this mumbo jumbo of timezone melts my brains. What am I missing here? I'm almost certain that storing all dates/times in UTC inside the database is the best. I just can't think crystal clear how do deal with it between the user and the database.
Your problem doesn't involve timezones at all, just the fact that clients can turn their clocks or have their clock skewed considerably. For that the fix is to poll the server every once in a while for an offset fix to use in calculations.
In fact, you don't even need date objects. There is a certain universal instant in time when the auction ends. Let's say it is 1375960662823. Right now, the universal instant in time is 1375960669199, so from that we see that the auction ends in 6 seconds (1375960662823 - 1375960669199 ~ 6000 ). It will end in 6 seconds regardless if I am in Morocco or Japan. Do you understand it yet?
To generate these numbers, on the client side you can call var now = Date.now() + skewFix where skewFix is the correction that needs to applied in case client has time skew or manually set their computer to wrong time.
In PHP, you can generate it with $now = time() * 1000;
This is rather a typical subject yet very complex for most to understand. First thing, you never mention the DAYLIGHT SAVING. yeah I am increasing your tension :).
Now let us see how we can do this. You did a good job by saving the Time in UTC. Now, I hope you have registered members and that each member has ability to set their preferred timezone, otherwise you will show Server' timezone based time to them.
When you through "start time" to user you must send them after converting UTC time to their time, similarly when you accept TIME from browser be it user action or javascript you need to convert that time to UTC considering the fact that user is that time zone that he select for his profile.
Hope that clear the idea on where you are going wrong? Please read through day light saving as that will play an important role too when you move ahead with other logic on same.
EDIT:
You can use javascript's Timezone offset, for auto submission and user input based on his settings.
Date in JavaScript uses local timezone. You should get UTC time for the user and send it to the server
new Date
Thu Aug 08 2013 17:00:14 GMT+0530 (India Standard Time)
(new Date("Thu Aug 08 2013 17:00:14")).toUTCString();
"Thu, 08 Aug 2013 11:30:14 GMT"
This will resolve the timezone issue between the server and client.
You said
( because auction_deadline = '2013-08-08 10:46:08' and NOW() = '2013-08-08 10:26:50')
In MySQL - NOW returns the current time in the server's local time zone (docs).
You probably want something like UTC_TIMESTAMP which returns the current time in UTC (docs).
Also - you probably shouldn't accept any input time from the client JavaScript at all. Only trust your own clock. When a bid is placed, use the time on your server in MySQL or in PHP. Don't accept it as input.
You can do the following
once page is loaded, send an ajax request to server with timezone offset of user. You can get timezone offset using the following code.
var curdate = new Date()
var offset = curdate.getTimezoneOffset()
offset is timezone offset in minute.
I think it will help.
everytime when you get the date from the clientside, you can use the getUTC to convert to UTC date ie:
var todayDate = new Date();
var todayDateInUTC = new Date(todayDate.getUTCFullYear(), todayDate.getUTCMonth(), todayDate.getUTCDate(), todayDate.getUTCHours(), todayDate.getUTCMinutes(), todayDate.getUTCSeconds());
so right before you insert the bid date to database, use the getUTC functions to convert it into UTC format.

Categories