Render date from date field in correct timezone? - php

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

Related

Any disadvantage using SET time_zone in MySQL PHP

I am using timestamp fields in my databases and my PHP software has its own time management system based on users timezone. I want to use timestamp fields for certain kind of data (created or modified when) and also be able to use te DEFAULT CURRENT_TIMESTAMP for the columns.
Is there any disadvantage setting the timezone to UTC using, SET time_zone = '+00:00', each time the session is created. I have four separate databases which the software uses and currently, I am setting the current timezone to UTC.
I don't want to use DATETIME as they are larger in size and also I won't be able to use DEFAULT CURRENT_TIMESTAMP as the timezone of the server might have an offset.
You should not use SET time_zone if your backend already uses all the logic into converting user's timezone correctly, because you're wasting resources unnecessarily. The UTC timezone should be into the metadata of the DB, where always the DB transactions will work with them.
By the way, TIMESTAMP columns always will be stored in UTC, so you don't need to setting that, unless your columns are datetime (not the case, i think).
When you insert a TIMESTAMP value, MySQL converts it from your
connection’s time zone to UTC for storage. When you query a TIMESTAMP
value, MySQL converts the UTC value back to your connection’s time
zone. Notice that this conversion does not occur for other temporal
data types such as DATETIME.
So you have two options:
Set the timezone in your transactions working with time in your sql;
Working with unix timezones into backend and only showing the correct converted time in the frontend to user.
I prefer the second one.
When dealing with date/time for entry date and/or modified date, it is better to use normal VARCHAR with the length of around 200 (or any other value that fits the full date) in order to store the full date and process your date/time in your PHP script. This gives you the flexibility to view your time based on the timezone defined in your PHP code. Click here to see available timezones in PHP.
You can also format the date/time in any possible format you want by simply using the date_format of PHP.
I have given a reference code below.
//This is the way you define your timezone in PHP code
date_default_timezone_set('Asia/Beirut');
//You can capture the date/time by using the below code. This will store "2017-05-28 23:55:34"
$date_time_registered = date('Y-m-d H:i:s');
//Retrieve the date/time and re-format it as you require. Below code will output "May", full month.
$retrieve_month_only = date_create($row['your_store_date_time']);
$retrieve_month_formatted = date_format($retrieve_month_only, 'F');
echo $retrieve_month_formatted;
You can refer to this link to find out about PHP date/time formatting.

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.

PHP & MySQL Timezones whilst supporting user-defined timezones

I'm working on something where the user can select their own timezone and the software will be able to be used by others on their sites as well but I want to make sure that the timezone within the database is always set to UTC.
Now I know how you set the default timezone for PHP, such as:
date_default_timezone_set('Australia/Sydney');
...but I'm not sure how to make sure MySQL is using UTC? ...and even once you have made sure it is using UTC I guess you would have to convert your PHP dates/times into UTC before passing it to the database?
I guess I am wondering about many different date formats such as TIMESTAMP, DATETIME & even UNIX EPOCH integer timestamps which would simply be stored as a int datatype for example.
Then there is the whole retrieving dates/times from the DB and converting it to the respective timezone and lastly how does DST come into all of this?
I know there is a lot of similar questions out there, but I guess none really answered all my questions.
MySQL's data type timestamp stores the dates in UTC. For this to work properly, MySQL uses server's time zone and does the date conversion. It converts the date from servers's current time zone to UTC for storage. This implies that the database server should never change its time zone for this feature to work properly.
When you send the data to such a database, you send the UTC time as well. The easiest way to do this is to format a result of time() according to what MySQL wants (m-d-Y H:i:s).
In PHP, when you format the date for insertion to MySQL, it's the best to use DateTime class. It lets you offset the date with the time zone information, meaning that you don't have to use date_default_timezone_set function - that can lead to mistakes.
An example of DateTime in action:
$date = '1.12.2015 13:37:37'; // Format is day.month.year hour:minute:second
// We create DateTime from custom date format, for the person who resides in Australia/Sydney time zone
$dt = DateTime::createFromFormat('d.m.Y H:i:s', $date, new DateTimeZone('Australia/Sydney');
// Now we change the date's time zone into UTC, and we can insert it into MySQL
$dt->setTimeZone(new DateTimeZone('UTC'));
// This is the formatted date-string that can be safely inserted into MySQL
$date_string_for_mysql = $dt->format('m-d-Y H:i:s');
Alternatively, you can use int type in MySQL for timestamp storage and insert result of time() but this has a huge disadvantage of not being able to use date-related functions.
for current session of mysql you can try something like
SET time_zone = timezonename;
for more details you can also look into this answer https://dba.stackexchange.com/questions/20217/mysql-set-utc-time-as-default-timestamp

Timestamp and form input date/time

I have not got any code built yet as I need to ask this question before I can start making it.
first what I am doing:
I am going to be making a tournament system on my website and I would like the tournament creators to choose a date and time that tournament will be active for signups and closed for signups.
I believe I will be using www.jongsma.org datepicker as I think it is very nice looking and easy to use for the end user. Link:here
The Question:
After sanitizing the input from the forms date/time do I need to specify for it to be converted from the users (Person inserting the time) local time to UTC before I store the data on the database or does it automatically convert the input from there local time to UTC when the data is being written to the database?
I am using MySQLite
MySQL accepts datetime in this format "Y-m-d H:i:s".
You can always convert different formatted dates into unix_timestamp with strtotime and turn it into mysql date format with:
$unix_time = strtotime($differentFormattedDate);
date("Y-m-d H:i:s",$unix_time);

PHP displaying stored time data, and storing time data while accounting for different timezones

I am creating this post, to get confirmation that i am understanding the process correctly, and also to get feedback on a few minor details on solving the issue of post times being displayed and stored correctly for users in various time-zones.
Storing the time
First step is getting the users timezone as a GMT offset format using a javascript function, and storing it in a session variable. For example, the $timezone variable will store GMT -4
$timezone=$_SESSION['time'];
Next, Once i have my users timezone. When the user makes a post, I store the post time in mysql database, I will need to store it as a UTC format. How do i do this? Currently when I store the time data. it is in the following way. My stamp field is datetime format, and i would like to leave it as such if possible.
INSERT INTO posts (stamp) VALUES (now())
What function do i use instead of now() to get the UTC format which will then be inserted into my database? I assume that I need to use a php function which will use the $timezone to produce the UTC date.
Displaying the time
Next, Once the UTC date is stored in the db. I need to display the data to the user based on the $timezone variable we set.
So when I display the time, I currently do
echo date('F d', strtotime($list1['stamp']));
Once i have stored the data as UTC time, this will display the UTC time, but i need to show the user the UTC offset for their timezone, so I will need to convert $list['stamp'] in UTC time to a the users timezone using $timezone. What function do i user for this?
tl:dr
This should be all I need to make this work. let me know if you see any suggestions, or items that i have not accounted for, and if you know what functions I need to use to convert the time to UTC to store in the database, and what function to use to convert the UTC time to display user, using the $timezone variable.
For inserting UTC time into the database:
INSERT INTO posts (stamp) VALUES (UTC_DATE())
UPDATE: This will only insert the YYYY-MM-DD into your database. If you need time as well, then use:
INSERT INTO posts (stamp) VALUES (UTC_TIMESTAMP())
Then for printing the date according to timezone:
$date = date_create($list1['stamp'], timezone_open($timezone)); //$timezone='Pacific/Nauru';
echo date_format($date, 'F d');
That should help get you started. Learn more about PHP's DateTime Class for Object Oriented Methods, and cleaner programming in general.

Categories