3

Is there Date expressions or function? I'd like to calculate a duration between a date field and today ? Is there a now(), today() function? i'd like this kind of math expression: now() - [field_arrival]

5 Answers 5

2

If you only want to display the duration between the given date and today in a view then you don't need any calculation.

Just use time ago display option and display your given date with this time ago option.

You will have the result something like this -- 1 year 3 months ago.

You can drop text ago if you don't need.

0
1

Check out time() function. It returns current unix timestamp. Difference of these two fields will give you the difference in seconds which you can convert to minutes/hours/days as needed.

$now  = time();
// If $field_arrival is not a Unix timestamp you can use strtotime() to convert it to UNIX timestamp first.
$diff = $now - $field_arrival;
1

Check out the Date Module. It has a sub module called Date Views which gives you what you want: http://drupal.org/project/date.

The generated sql isn't pretty though. If you can use hook_views_query_alter instead you really should since you have better control over the result sql.

Image of the Date filter

1

I managed to do this by setting the output format in my source field to timestamp, via custom date format string: U then in the expression field I used:

time(0) - [field_fieldname]

Now you can see the offset in seconds from now and the field's timestamp, you can convert that into whatever you need with maths, ie:

Hours:(time(0) - [field_fieldname]) / ( 60 * 60 )

Days: (time(0) - [field_fieldname]) / ( 60 * 60 * 24)

Etc.

Turns out the ctools module expects maths functions to always take parameters, the correlated php function is time(void); so no matter what you put in there it will simply return the current timestamp. Hence the time(0).

0

my approach

$rawtime = \Drupal::database()->query( "SELECT NOW() as currtime " );
$timeObj = $rawtime->fetchAll();
2
  • Did you try this? Because I can't see it working inside Views' Global: Maths Expression input..
    – Grizly
    Commented Aug 11, 2017 at 3:21
  • yes , i have tried in controller not in views Commented Aug 11, 2017 at 4:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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