Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the recommended way to store current time using PHP and MySQL?

Tags:

php

mysql

gmt

My initial approach was:

$current = time(); // save this to column CURRENT_TIME with column type VARCHAR

//retrieve it like this
$retrieved = mysql_query(....) //assume query for getting the stored time value
$time = strtotime($retrieved);

I have come across the following approaches:

  1. use gmstrftime to handle gmt
  2. use INT instead of VARCHAR for the column
  3. use the mysql function CURTIME or CURDATE
  4. use the UNIX_TIMESTAMP mysql function

none of which were using the DATETIME or TIMESTAMP mysql var type.

Do you have a better approach for this one?

like image 557
yretuta Avatar asked Feb 24 '10 05:02

yretuta


3 Answers

It is recommended to use mysql timestamp (YYYY-MM-DD HH:MM:SS) field type to store time and date variables in mysql.

$sDate = date("Y-m-d H:i:s"); // 2015-04-07 07:12:51
mysql_query("insert into `table_name` set `created_on` = '$sDate'");

It gives you ability to use mysql functions to compare dates, calculate time differences and so, directly in your mysql query.

Also you can always retrieve the timestamp using strtotime() function.

$result = mysql_query("select `created_on` from `table_name`");
$row = mysql_fetch_row($result);
$iTimestamp = strtotime($row[0]); // 1428390771
like image 56
Alexar Avatar answered Nov 04 '22 14:11

Alexar


I just use the TIMESTAMP value type in MySQL, and let MySQL use its own CURRENT_TIMESTAMP.

like image 36
casraf Avatar answered Nov 04 '22 13:11

casraf


Well, you can turn a MySQL TIMESTAMP field into a PHP Time() value by using strtotime()

Then you just have to make a function that correctly turns a PHP Time() value into a MySQL TIMESTAMP value.

like image 24
Tyler Carter Avatar answered Nov 04 '22 12:11

Tyler Carter