Inserting TimeStamp into MySql Database via php - php

This question might be stupid but i am really curious on what is the recommended way. I am making demo rest api for my iOS app. I am iOS programmer and getting into learning php to write my own quick demo api.
On one of my table i have column of type TIMESTAMP. I am sending unix timestamp value to my api that will insert that value into that column.
I checked database and default timestamp value format is stored like
2015-04-15 16:48:25
and unix timestamp is like
1430233486
My API receives unix timestamp from my iOS app. Now my question is do i have to convert this timestamp that my app sends to the format that mysql saves ? I need to save data in single format. One more info: Sometimes if timestamp is not sent by app, then mysql inserts the current timestamp itself and this current timestamp is in format 2015-04-15 16:48:25 again.
My preference is to save in traditional unix timestamp format. Is there any settings/query that if mysql decides to store current timestamp in column than its always in 1430233486 format ?
Note: My assumption is that TIMESTAMP type in mysql means unix TIMESTAMP. There are DATETIME type too in mysql. I may be wrong with my assumption as i can simply use INT type for storing my unix timestamps but i like the feature of mysql inserting current timestamp as default without business logic code if i don't provide any timestamp from app.

As far as I know, There's no a dedicated field's type for unix timestamps in mysql. Unix timestamps are actually signed 32bit integer, therefore you can use the INT type to store them.
Please be aware to the range of the INT type field (https://msdn.microsoft.com/en-us/library/ms187745.aspx). I believe that INT would work for you, but just in case you're dealing with off-the-range numbers, you might need to use BIGINT.
In my opinion, you should store the unix timestamp rather than the formatted date/time option since it's easy to manipulate, for calculations or reformatting.

I recommend you to don't use 2 different types of data into the same column of database, is not data consistent.
I recommend you to do a function or method that compares if the value is a string or a number and then convert it to a datetime or timestamp.
Like for example:
function convertTime($value) {
if (is_numeric($value)) {
return date("Y-m-d H:i:s", $value);
}
return $value;
}
Or to convert from date to unix timestamp:
function convertTime($value) {
if (is_string($value)) {
return strtotime($value);
}
return $value;
}
and use that function to everywhere.

Related

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

Storing timestamp in MySQL

I'm grabbing data from a webpage that returns a timestamp in the following form (which is a string):
2013-11-09T15:14:48.957604
How can I interpret this in PHP, and what is the best way to store this in a MySQL database?
The best way to store it is to use the MySQL DATETIME data type. It is specifically meant to handle date/time values, and it works beyond the year 2037, which is the approximate limit using unix timestamps. MySQL and PHP both handle these values with ease using built in functions/libraries (for PHP, see the DateTime class as mentioned by another commenter).
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
http://php.net/manual/en/class.datetime.php
I just want to expand on the information given here.
This will convert the string into a DateTime object.
$dtObject = new DateTime("2013-11-09T15:14:48.957604");
But, in order to store the timestamp in the database there are several requirements.
Needs to be in Y-m-d H:i:s format.
MYSQL column type must be datetime/timestamp
Needs to be a string.
Now in order to get this timestamp into a MYSQL friendly format we need to use the format function.
$timestamp = $dtObject->format('Y-m-d H:i:s');
You can now INSERT this into the database. You can also output the same way following these date formats.

Can someone please clarify how MySQL's TIMESTAMP is used in conjunction with PHP's DateTime class?

I've been studying the differences in usage between MySQL's DATETIME and TIMESTAMP. It seems that it's pretty straight forward with DATETIME. I would use the following procedure:
Choose the default timezone for all dates, such as UTC.
Let user select a date from drop-down.
Create new PHP DateTime object with the chosen date, using the user's timezone settings, such as EST.
Convert the object to UTC, and insert into database.
On another page, retrieve datetime value and make a new DateTime object with it, using UTC timezone.
Convert object to user's local time (EST), and display to him.
Now, it seems that mysql's TIMESTAMP column type can help eliminate all of these conversions.
What would the above steps look like with the TIMESTAMP column type?
Would I need to do "SET time_zone = timezone;" in the beginning of each pageload to set the timezone to the location of the user?
Would it be easier to ONLY use one type of date column type per database? If not, it may require two different sets of functions to produce the right date.
Should TIMESTAMP only be used in columns not intended to be shown to the public (so as not to deal with formatting)? Like when a row was created, last edited, etc.
I have not tested any of this approach, but it seems pretty straightforward =)
You shouldn't need to convert dates, just set the time zone when you
read/write from dB to get everything right.
Yes, you will have to set right time zone after connection to dB is made.
You mean to only use datetime or timestamp? It really depends on how you intend to
use the columns. But there isn't a clear have to do.
Same as above, it isn't wrong formatting your data from the dB, with a timestamp you can return date style strings from the dB so no worries
Traditionally timestamp is associated like you mention, and datetime for other dates.
more on locale/time zone:
MYSQL set timezone in PHP code

Can PHP safely use unix timestamps to query mysql database?

There's lots of recommendations out there about handling dates. I'd just like to clarify something. Let's say:
user is inserting records into a database
unix timestamps of insertion date are generated for this record
Now the user wants to query a date interval in the database:
user provides 2 dates in his local timezone
use these values to convert timezone to UTC and get the timestamp
query the records in the database based on the 2 integers from conversion (eg. WHERE date >= FIRST and date <= SECOND)
convert the retrieved timestamps to local timezone again for display
I know that would be possible with PHP, but and wouldn't need to care about mysql's timezone settings in this case - only php's. The system would be 64 bit so running out of space to store the date is not an issue. But ...
Would that raise any other serious issues like with DST changes or something else?
Unix timestamp is timezone-independent.
This is also the reason you can change this step:
use these values to convert timezone to UTC and get the timestamp
into this:
convert values to Unix timestamp
Although storing timestamps in the database (eg. MySQL) is very simple. You can make sure PHP has Unix timestamp, if you will:
save the values by using FROM_UNIXTIME() MySQL's function (give Unix timestamp as argument and you will receive datetime according to MySQL's settings),
retrieve the values by using UNIX_TIMESTAMP() MySQL's function (give the name of the field, or the value, as the argument), so you will get Unix timestamp (integer) on the basis of datetime stored in the database according to MySQL's settings.
Just remember to use TIMESTAMP column type to store timestamps. This way the time will be stored in timezone-independent manner, only displayed according to MySQL's settings.
Tadeck is correct that Unix timestamps are timezone-independent.
But when using timestamps throughout your application you should store and use timestamps in the database as plain INTs. Convert to and from local timezones at the application level (in PHP). That allows you to only concern yourself with timezones in PHP and not in 2 systems. It also eases setting time zones for individual users at the application level.

What's the best way to store date and time in a MySQL database for later display with PHP?

I want to store the date and time that a user performs an action on my website into a MySQL database. I'd like to be able to do the following with ease:
Store the date and time as one field in the database
Use a built in PHP or MySQL function to generate the date-time of the action
Store the date-time based on my server's time, and not worry about user timezones.
Order By the date-time field when I query MySQL
Later, display the date-time in many different formats using built in PHP methods
Here are my questions:
What data type should I use in MySQL ( eg. timestamp, datetime ... )?
What method should I use to generate the date-time ( eg. MySQL's now(), PHP's date() ... )?
What PHP method should I later use to format the date-time in various pretty ways ( eg. 23/4/2012, 5pm on Monday, July 2012 ... )?
I would store it as a datetime, not a timestamp.
I normally use the PHP date function and that way if you ever want to store the time relative to the user's timezone you can simply change the timezone based off the user's settings.
When you pull it out of the database, use strtotime() to convert it, then you can use all the date() features to display it however you want. Example:
echo date('F j, Y',strtotime($db_datetime)); //Displays as 'March 5, 2012'
I've struggled with this question for years, and I'm beginning to think that the best way might be to store the time as an integer that represents Unix time (number of seconds from Jan 1, 1970). I've done this and it works fine.
Personally I've never used datetime, and I can't think of a situation when I ever would use this. It just carries too many problems with it.
Timestamp is a lot better, but in MySQL it can't store a date later than 2032.
I would love to hear some serious discussion on this topic, but Stack Overflow might not be the best place for this.
If you set the mysql data type to a non-nullable timestamp, then save rows with a null value for that column, mysql will automatically update the timestamp for you.
As for reading it back out again, you can just use php's strtotime and the date object to get it into the format you need.
You should use the datetime datatype for your requirement.
It will store both the date and time from your input field based on your query.
For retrieving the datetime you can use the mysql's date_format() function or PHP's date() function.
The datetime will always be stored according to the server's time and not on the clients time.

Categories