PHP time() function and MySQL fields - php

If I use the PHP's Time() function and in MySQL there are 4 fields DATE, DATETIME, TIMESTAMP, and TIME, which one I should use?
In PHP I use the Time() to record both the Date and the time like 5/10/2012, and the time is used to calculate the time elapsed.

Use what you need:
DATE:
stores only days ex: 2012-06-11
DATETIME:
stores days and time ex: 2012-06-11 12:49:31
TIMESTAMP:
stores days and time ex: 2012-06-11 12:49:31
MySQL has function that sets this field to current timestamp, when there was update in the row.
Maybe (don't know right now) can be specified by number. Others must be specified 'yyyy-mm-d hh:mm:ss'
to convert DB value to PHP's time use strtotime()

I would suggest you to use MySQL Data And Time functions instead. If you need to store current time, use NOW(). It's DATETIME type. Alternatively, you can use Unix Timestamp storing it as INT.

The Unix timestamp is the most basic form of a time/date- a "raw format", if you will. Once you have a timestamp, you can get to any other format you want. Personally I don't see the point in storing DATEs or DATETIMEs, only to convert it to a timestamp when you retrieve the data again, which of course you will need to do if you want to display a date/time in any readable format (see date() function).
MySQL has a field time that store the current timestamp when a record is created. Alternatively, and if you want more flexibility, PHP's time() function returns the current timestamp. PHP also has functions for calculating the timestamp at a certain point in time (e.g. if you want to specify a date in dd/mm/yyyy format).
So in summary, I would always use timestamps, and I recommend you do too, unless you have very specific needs.

Related

How do I set the time in a MySQL timestamp?

How do I change just the time in a timestamp (say, from 2014-08-08 14:26:15 to 2014-08-08 08:00:00)? In PHP I would probably get the timestamp from MySQL, modify the time, then update the table, but I figured there might be a function for doing so in MySQL alone.
(I know timestamps are not used for this purpose, and that a datetime would be better, but I don't have control over the DB schema.)
You can format a date (or datetime) into a datetime string, and specify a hard-coded time, ignoring any time component that may be in the original value.
DATE_FORMAT(datecolumn, '%Y-%m-%d 08:00:00')
See http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date-format for reference doc on that DATE_FORMAT() function.

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.

PHP -Comparing Unix Timestamp To Now

I'm retrieving a unix timestamp from a DB and I want to check if this datetime has passed already.
I tried using an if statement to compare to time() but it always says the time has passed already.
What am I doing wrong?
EDIT: Just some more info..to determine am/pm I'm adding 12 to the hour if its PM before running it through mktime(). (Is this right?)
It's stored in the DB as int not as any datetime types.
Your PHP time could be affected by PHP's timezone. Use date_default_timezone_get() to find out what time zone you're in.
Make sure the timezones in the DB and PHP are the same, use NOW() function to fill the DB column with current timestamp (the column should be of datetime type), then you can get the timestamp using UNIX_TIMESTAMP() MySQL function which compares against PHP's time() just nice.
Alternatively, you can fill the DB column with something like
mysql_query("INSERT INTO your_table (your_date) VALUES (FROM_UNIXTIME(" . time() . "))")
That should work even with timezone discrepancies.
If you are using mktime to create a UNIX timestamp, PHP is using the timezone settings to interpret what you mean by the given parameters. It's possible that you should be using gmmktime. It depends on how the timestamps in the database are being created; I cannot say for sure without seeing more code and having a more detailed explanation.
I generally prefer to simply store all dates as DATETIME types in the UTC (GMT) timezone. It tends to be less confusing.
Just some more info..to determine am/pm I'm adding 12 to the hour if its PM before running it through mktime(). (Is this right?)
12 PM is hour 12.
1 PM is hour 13.
So you don't always add 12. (i.e., 12 Noon is the exception).

date problem in php

In my php application I have this code:
<?php echo date("d/m/ Y ",strtotime($row["m_date"]));?>
In it, $row["m_date"] is fetching from a database.
The problem is that all the dates are printing perfectly except 27/2/2011. It's printing 1/1/1970 instead.
The date in the database is fine, and prints correctly in a PDF.
I'll assume you're getting the date from the database as the string 27/2/2011 because that's most probably what happens (correct me if I'm wrong).
PHP considers the string 27/2/2011 as being in the m/d/Y format, not d/m/Y and tries to parse under that assumption. Because the date is not valid under that format strtotime returns false. Giving false as the timestamp parameter to date is taken as 0, which is the timestamp for January 1st 1970.
What you need to do is either get your date in another format (or better still, as a timestamp) from the database, or parse it yourself (say using explode).
Good luck,
Alin
The database should be able to return the date to you as a UNIX timestamp. For example, MySQL has the UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(date_column) FROM table;
Postgres has date_part
SELECT DATE_PART('epoch', date_column) FROM table;
Most other databases should have similar features. If you can get the date out as a UNIX time stamp you can pass that directly to date() without having to use strtotime() as well.
All of this does of course assume you're using a temporal datatype for the columns in question (timestamp, datetime, timestamp with time zone, etc) and not just storing a string. You are using a temporal type, right? If not, then why not?
if you are storing the date in the database as a timestamp this should work
<?php echo date("d/m/Y",$row["m_date"]);?>
if you are storing the date in the database as a date or datetime this should work
<?php echo date("d/m/Y",strtotime($row["m_date"]));?>
How is the m_date stored in the databases? Is it a datetime object? Or a string.
Problem with strtotime is that it isn't real good at deciphering written dates. So something like 27/2/2011 gives problems while 27/02/2011 gives no problems at all.
So there are 2 solutions:
Make sure all the dates that get entered into the database are of the correct format (dd/mm/yyyy).
Write a regular expression that adds a leading zero to all single characters.

Categories