Often you have to see how a real circus begins, when a PHP programmer comes to date. Here there are self-written magic functions that calculate something there and constantly stumble at the border of months or years, or when switching hours to winter / summer time, here and the mysterious use of built-in functions, with tambourines and dances.
And it is necessary, in fact, almost always quite a bit.
Under the cut - a couple of useful, in my opinion, tips for novice programmers.
')
Everything is simple: we give this function a text description of the date, we get timestamp at the output. Hints here are such (this is, in general, for those who are too lazy to follow the link):
1. using relative date descriptions (for example, "-1month" is the current date minus 1 month, "+ 1year + 1month" is the current date plus 1 year and 1 month)
2. The use of the second, optional parameter $ now is the timestamp relative to which the date is calculated. For example, display the date - Friday of the following week:
$ now = strtotime ("this sunday");
print strftime ("% c", strtotime ("next friday", $ now));
Why it was impossible to use simple
strtotime here ("next friday") ? Yes, because if today, say, Thursday, then strtotime (“next friday”) will give us back time stamps of the next Friday — that is, Fridays of this week, but this is not what we need (though we could use
strtotime (“ next week friday ”) , but shh).
Another example. Calculate the date - the first Monday of the next month.
$ next_month_fisrt_day = date ("Ym-01", strtotime ("next month"));
$ next_month_fisrt_monday_ts = strtotime ("this monday", strtotime ($ next_month_fisrt_day));
print strftime ("% c", $ next_month_fisrt_monday_ts). "\ n";
This function returns a date formatted with the current locale in the specified format. Often it can help, for example, to abandon the use of arrays with the names of the months - in favor of the built-in features of the language.
Happy programming!