Skip to content
Advertisement

Calculating time difference returns null [closed]

I am trying to select everything from the post and calculate the time difference between you and when it was posted and I am using

SELECT FLOOR(TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, post.created) / 60)) 
FROM post

as my query to calculate it to minutes but when I execute this query some of the records return null and I do not know why this is

2021-12-16 21:31:09 the query does not work for this date

2021-12-18 17:01:37 but for this one it does

does anyone know a fix?

Advertisement

Answer

Based on this fiddle, it looks like it’s failing at the TIME_TO_SEC() call:

SELECT FLOOR(TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, post.created) / 60)) as result,
   timediff(current_timestamp, post.created) as step1,
   TIMEDIFF(CURRENT_TIMESTAMP, post.created) / 60 as step2,
   TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, post.created) / 60) as step3
FROM post

Results:

result step1 step2 step3
null 45:09:30 7515.5000 null
151 01:39:02 231.7000 151
null -46:20:58 -7700.9667 null
null 838:59:59 139765.9833 null

This is the kind of debugging step you ought to be able to take on your own :/

However, it is reasonable to still need help after narrowing the problem as above, and with that in mind this is probably the result of a mis-placed parentheses. It seems like you’re want to divide by 60 after the TIME_TO_SEC() call:

FLOOR(TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, post.created)) / 60)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement