1

Is it possible to convert timestamp to date format when I do $query?

Right now I do query and then convert timestamp to date format which affects performance and also looks wrong :)

Current logic/code

$query = db_select('my_submissions', 's');
$query->fields('s', array('sid','name','company','email','phone','is_customer','submitted','count'));
$entries = $query->execute();

$rows = array();
foreach ($entries as $entry) {
  $row = array_map('check_plain', (array) $entry);
  $row['submitted'] = $row['submitted'] ? date('d.m.Y H:i', $row['submitted']) : "";
  $rows[] = $row;
}

How can I define transformation of timestamp to date in query? is it possible?

2
$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(submitted), '%d.%m.%Y %H:%i')", 'submitted_formatted');

http://www.w3schools.com/sql/func_date_format.asp

then in your loop, reference it as $row['submitted_formatted'];

  • 1
    This won't take into account the user's timezone. – mpdonadio Nov 8 '16 at 14:24
1

MySQL allows converting a timestamp into a formatted date, using the FROM_UNIXTIME function.

In your case, instead of the 'submitted' field, you might add an expression to the query with the addExpression method, in the following way:

$query->addExpression("FROM_UNIXTIME(submitted, '%d.%m.%Y %H:%i')");
  • 2
    This won't take into account the user's timezone. – mpdonadio Nov 8 '16 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.