2

Is it possible to convert a timestamp to a date format in a query?

This is the code I am using.

$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;
}
4
$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'];

  • 3
    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')");
  • 3
    This won't take into account the user's timezone. – mpdonadio Nov 8 '16 at 14:24
0

While

$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(yourDBcolumn), '%d.%M.%Y')", 'c.yourDBcolumn_formatted');

Does indeed work, this is definitely not best practice if you're displaying this on a page/block.

A themer/front-end dev shouldn't have to go into PHP code to change the format of the date.

It's best practice for your custom module to have a template file where they can easily format it with Twig's |date filter

{{ mydate|date }}           <!-- November 17, 2019 23:12 -->
{{ mydate|date('d/m/Y') }}  <!-- 17/11/2019 -->

Also, you could add timezone here, ex:

{{ mydate|date('d/m/Y', 'Europe/Paris') }} 

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.