I have a timestamp stored in my database, for example: 10-02-2021 11:34:00.
I’d like to display a real-time countdown in a text field, showing the time elapsed since this date until now. It should look something like: “1277 days, 23 hours, 59 minutes, and 0 seconds” with the seconds counting down in real-time.
@hugoalves great question! This can be solved in native Bubble which is nice. I’m sure there is more than one way to solve this, but I’ll point you towards a solution.
First you want to reset a date every second. This will allow you to get the real-time countdown since every second the date would be updated. You’ll want to store this in a custom state so that you can access like this:
Note that this value is of type “date”. This will allow us to subtract our two dates which Bubble handles nicely. So you want to subtract your “Event Date” from the date in the custom state above which is now changing every second.
When you do this subtraction you will end up with a value in seconds; the number of seconds difference from these two values. The only remaining tasks is to display this in a human readable format (e.g. days/hours/mins/secs) which is a small bit of math.
Days ([seconds difference] / 60 / 60 / 24):
Hours ([seconds difference] / 60 / 60):
Minutes ([seconds difference] / 60):
Seconds([seconds difference])
There is one small detail that is not explained yet. You will note at the end of each date subtraction (with the exception of “Days”) there is an additional subtraction. This is subtracting out all of the previously accounting for “time”. That is to say when we get the difference in “hours”, we don’t want to include all of the days that we have already accounted for in the “Days” total, we only want the remaining hours left in the difference (e.g. “Event Date” - “Current Date” = 22 days 8 hours, to get 8 hours we need the total number of seconds difference with the number of seconds in 22 days removed. If we don’t remove 22 days then we would get 22 days * 24 hours + 8 more hours which would be the total number of hours until the “Event Date”. This would be correct if we trying to specify “hours” until the event. Since we are trying to break it out into days/hours/minutes/seconds we must remove all of the previously accounted for time.
The trick in Bubble is to use an input fields rather than a text fields so that we can easily reference the value in the calculation. Also note the “copy” as we use one input field to store/display and a different field to store/calculate.
This is a solution but it’s resource intensive as it triggers a workflow every single second. I think using a plugin, like it’s been pointed out here is the best way to go about it