Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 - How to insert unix timestamp into database

Drupal newbie question. I'm trying to insert the current date/time into a SQL database as a unix timestamp. It's working in that I'm not getting an error but it just inserts the same value every time (2147483647). I'm working on a localhost (if that makes a difference) and have tried the following, all to no avail:

format_date(strtotime('now'), 'custom', 'YYYY-MM-DD 00:00:00'); 

format_date(time(), 'custom', 'YYYY-MM-DD HH:MM:SS'); 

format_date(mktime(), 'custom', 'YYYY-MM-DD HH:MM:SS');
like image 587
purplerice Avatar asked Sep 10 '11 21:09

purplerice


2 Answers

The PHP function time() return the current UNIX timestamp. equivalent with strtotime("now"). ALso if you want to insert in the database the current timestamp you can create the field in the database as TIMESTAMP with the default option CURRENT_TIMESTAMP or even directly in SQL you write my_time_stamp_field = NOW().

Also...if you have a custom date you can use mktime() http://www.php.net/manual/en/function.mktime.php The unix timestamp is an int value, in you example you want a formatted datetime, if this is the case use date('YYYY-MM-DD HH:MM:SS', time()/unix timestamp/).

Hope it helps.

like image 173
Anti Avatar answered Sep 24 '22 15:09

Anti


Just want to provide more details with the comments of purplerice.

we can use REQUEST_TIME - Time of the current request in seconds elapsed since the Unix Epoch.

http://api.drupal.org/api/drupal/includes!bootstrap.inc/constant/REQUEST_TIME/7

    $inserted_val['other_value'] = 'other value';
    $inserted_val['last_update_date'] = REQUEST_TIME;
    db_insert('tablename')->fields($insert_fields)->execute();
like image 38
cww Avatar answered Sep 22 '22 15:09

cww