date of Yesterday
|
Author: Mattias (mattias@999tutorials.com) Categories: PHP |
|
Today we help you with "The date of yesterday". |
|
The tutorial: Digg this, Post to del.icio.us, One thing that I almost always have to double check when programming PHP is date handling. Simple things like "What's the date yesterday" can be hard to remember exactly how to program. The good and bad thing with PHP is the broad range of functions, but in the date/time world I think it's a negative thing for PHP. (The calendar functions might solve this though). Yesterday's date the "hard way"$yesterday = mktime (date("H"), date("i"), date("s"), date("m"), date("d")-1, date("Y")); mktime is a powerful function that can be used for this, and some other problems. The problem is that it is a little bit overkill for our need at the moment. Because of this the PHP code just becomes to hard to read, and this is a huge problem if you are a team of programmers of if you go back to your code later on. What happens in this code snippet is that we use date for getting the numbers for current: hour, minute, second, day, month and year. The "day number" is decreased with One to get yesterdays date. All this numbers are passed to mktime that makes a representation of the date/time in unixtimestamp. The unixtimestamp is converted to readable format like this: 2008-02-25 (swedish date format). Yesterday's date the "easy way"echo date( strtotime("-1 days")); This is pure beauty if you compare the the "Hard way version" above. Not only is it shorter and more "beautiful", it is also a lot easier to understand what happens when just looking at the code for half a second. Let's say you want the day before yesterday. Just write this: echo date( strtotime("-2 days")); What's the date next week from today? echo date( strtotime("+1 weeks")); ConclusionThere are more than one way to solve lots of PHP (and other) problems. It pays of to try to find the best and most beautiful solution. You will gain in lots of ways for this work you do. Next time you look at it (let's say a year away) you will still understand what happens in the code. There is a saying that code is "consultant friendly". That is when you write simple code extremely hard so no one else can be hired to do you work, and they need to hire you. I disagree with this a lot!! If you do you work good you will be hired again, and writing code that is simple to understand will produce better result and higher chance of doing error free code. So you have everything to win on writing good code AND comment your code!
Happy date and time programming :-) Digg this, Post to del.icio.us, |
