Get current timestamp in PHP in phpmyadmin format - php

In phpadmin we can assign default value as current timestamp for a field.
How can we generate timestamp in similar format in php.
For eg.: 2014-09-07 03:18:35.000000

Pretty simple in PHP:
date('Y-m-d H:i:s', time());
Where time() outputs the current time measured in the number of seconds since the Unix Epoch. It'll be based on your server clock. You can replace time() with any other timestamp or PHP function that generates a timestamp, like mktime(), strtotime(), DateTime::getTimestamp(), etc.

Related

PHP mktime and timezone

I'm working on some time related features and I opt to always use UTC times and store time stamps as integers for consistency.
However, I noticed that when I use mktime it seems that the currently set time zone has an influence of the return value of mktime. From the documentation I understand that mktime is supposed to return the number of seconds since epoch:
Returns the Unix timestamp corresponding to the arguments given. This
timestamp is a long integer containing the number of seconds between
the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
http://php.net/manual/en/function.mktime.php
However, it seems that mktime is including the time zone that is currently set. When using the following code:
date_default_timezone_set('UTC');
$time = mktime(0, 0, 0, 1, 1, 2016 );
echo "{$time}\n";
date_default_timezone_set('Australia/Sydney');
$time = mktime(0, 0, 0, 1, 1, 2016 );
echo "{$time}\n";
I would expect the two time vales to be same but apparently they are not:
1451606400
1451566800
Which seems to be exacly an 11 hour difference:
1451606400 - 1451566800 = 39600 / (60*60) = 11
What do I not understand correctly about mktime and/or why is the time zone taken into account when using mktime?
I can't tell you why it is the way it is (PHP has never made sense to me when it comes to date and time) but there is an alternative function gmmktime() which is
Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.
There is also a comment on the PHP documentation for this function which explains how mktime(), gmmktime() and time() work. Essentially, they assume that you always think in time zones even if a UNIX timestamp itself doesn't carry a timezone.
Resulting Unix timestamp are indeed encoded in a timezone agnostic way, but input arguments are interpreted relative to the timezone set for current process. And indeed, Sidneys 2016-01-01 00:00:00 (GMT+11) happened 11 hours before UTC 2016-01-01 00:00:00.
When some foreigner tells you a time, you have to know its time zone to correctly interpret it, and so does mktime().
If dates you want to pass to mktime() are UTC dates, then use gmmktime() which exists for that purpose.

Generate Datetime in the future without UNIX timestamp

Lets say today is the 08.20.2014.
I want to get the date from "today" additional 30 years (08.20.2044) with PHP and insert it into my mysql Database with it´s Datetime field.
How do I correctly generate the YYYY.MM.DD H:i:s without using the UNIX timestamp?
If i use
mktime() -> I get a UNIX timestamp (Limited, has a maxyear 2038, so nonsense)
time() -> I get a UNIX timestamp
date() -> I need a UNIX timestamp
strtotime() -> Im converting from/to UNIX timestamp
Am I completly missing a point?
What is the sense of using DATETIME if I´m using the UNIX timestamp in my code which is limited (I know that DATETIME is also limited to the year 9999)?
Don't use unix timestamps in your code, use DateTime class.
$time = new DateTime();
$time->add(new DateInterval('P30Y'));
echo $time->format('Y-m-d');
it prints 2044-08-20

Why can't I use php time() for a timestamp column?

I have a timestamp column in a db table. Saving values with:
UPDATE `table` SET `activated_at` = CURRENT_TIMESTAMP WHERE `id` = 123;
works fine.
But when I use the php function time() to get the timestamp, it doesn't work. It only works using date('Y-m-d H:i:s') for the column value. Question is why?
the column definition is:
`activated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
I'm using the php mysql extension (and yes, I know it's deprecated, but I have to maintain some legacy code)
Since time() in php return a unix timestamp and timestamp is a datetime type and it requeires a valid datetime value.If you didnt give a valid datetime value it will be storing like 0000-00-00 00:00:00. If you want to keep your field as datetime type then you must give date('Y-m-d H:i:s') in php
Also check the documention of various date time types in mysql
time() returns a unix timestamp, but the MySQL timestamp column supports specific formats such as YYYY-MM-DD HH:II:SS. You can easily do the conversion using date for PHP or FROM_UNIXTIME in mysql.
Look here
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
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. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of the time_zone system variable. For more information, see Section 10.6, “MySQL Server Time Zone Support”
*nix timestamp and MySQL TIMESTAMP is not the same... that's why you need convert from *nix timestamp to MySQL timestamp over date('Y-m-d H:i:s', $unix_timestamp)
if you want to use time() change the column type to varchar(15)

How to calulate the difference between a MySQL timestamp and the current time in PHP

I'm trying to calculate the difference between a timestamp retrieved from a MySQL database and the current time.
Appreciate the help.
As mentioned by #RemoteSojourner, I got the current time in a UNIX timestamp format (which returns time in seconds), I got the timestamp from the DB (using an ORM) and converted that to a UNIX timstamp too and then subtracted the two timestamps.
$current_time = strtotime("now");
$last_access_time = strtotime($this->last_access);
$inactivity_duration = $current_time - $last_access_time;
This example makes the difference between now and one hour ago.
select timediff(now(), now() - interval 1 hour)
You can use the strtotime function to parse the MySQL timestamp into a Unix timestamp can be further parsed or formatted in the PHP date function.
Retrieve the datetime from mysql like this
SELECT UNIX_TIMESTAMP(`time_col`) FROM `tablename`...
AND compare it to time()

What's the difference between PHP time and SQL time?

Why is the timestamp generated by the PHP time() function so different from SQL datetime?
If I do a date('Y-m-d', time()); in PHP, it gives me the time now, as it should. If I just take the time() portion and do:
$now = time();
//then execute this statement 'SELECT * FROM `reservation` WHERE created_at < $now'
I get nothing. But hey, so if the value of $now was 1273959833 and I queried
'SELECT * FROM `reservation` WHERE created_at < 127395983300000000'
then I see the records that I have created. I think one is tracked in microseconds vs the other is in seconds, but I can't find any documentation on this! What would be the right conversion between these two?
The time() function doesn't return microseconds, so it should work if you're using the correct datatype. But you have 2 different datatypes right now, INT and a date field (could be DATE/DATETIME/TIMESTAMP). If you want to compare a date in the database to a timestamp as integer, you could use something like:
SELECT * FROM Tbl WHERE UNIX_TIMESTAMP(date) < $timestamp;
time() gives a Unix timestamp (seconds passed since 01-01-1970) - SQL wants to have timestamps in format YYYY-mm-dd hh-ii-ss which is done by date() - so if you don't want to call 2 PHP functions, just use $now = date("Y-m-d H:i:s") or, better, change your SQL query to created_at < NOW().
They're just 2 different ways of storing dates, each with their advantages and disadvantages. You can use MySQL's date field, or simply store unix timestamps in an INT field. You can also use:
SELECT UNIX_TIMESTAMP(field_name) FROM ...
to return a date field as a Unix timestamp.
The MySQL date field is human-readable and can store any date in the foreseeable future. However, it does not store timezone information which can cause serious issues if not handled correctly. Facebook had this problem a while back.
Unix timestamps store timezone information (since it's defined as the number of seconds since 12:00am January 1st 1970 UTC). Comparison operations are faster on integers, and PHP's time/date functions are designed to be used with Unix timestamps. However, Linux can only support dates from 1902 to 2038 and on Windows from 1970 to 2038. MySQL and architecture in general will switch to 64-bit integers long before 2038 arrives, but if you need to store dates that are in the distant future or past, Unix time isn't for you.

Categories