- Luke Johnson
- February 5, 2020
- Reading time:
- 2 minutes
- Ask a question
- Email Luke
There are many occasions in coding when time is a factor in a website's functions. For example, if your website stores information in cookies, you will need to state when the cookie should expire. But different cookies will need different expiry dates. You might want your admin login to last 4 hours, but perhaps you need your public website's cart to remember a customer's selections for a couple of weeks.
Time calculations in most cases requires a time string expressed in "seconds". But it can be a pain to do the math every time to find the numerical equivalent of "4 hours" or "2 weeks" or "a year". It's a waste of your time to run manual time calculations over and over again.
Here is a quick function to make this a much simpler process.
First, declare the common time units: second, minute, day, week (and fortnight if you like).
Then, notice, the function takes the arguments
$unit allows you to put in a representative word such as "day", and to declare with
$amount how many you need.
I set the default value to "1" so that if you need a single hour or day, you can leave
$amountout and simply call
By putting all your time units in an array, you can call the unit you need by requesting a unit with
Now when you need to grab a quick expiry date for a cookie, or a time calculation for another use, it is as easy as calling
calcTime('week', 2). No more repetitive math.