The Idea
It is often a nice feature to show users the current date or calculate a date in the future dynamically. The idea used here could be helpful in a payment processing script where a persons payment is due one month from the start date.
The Solution
PHP has a native function for just this task, called date(). The date function accepts either one or two parameters: a string or a unix time stamp. Now one idea you have to understand, is since PHP is a server-sided programing language, the date being displayed is the date of the server, NOT of your local computer.
To display the date you could simply go like so:
Which will display something like 2007-01-10. You can change the output of the date by changing the string parameters. For example you could do:Code:<?php
echo "Today is ";
echo date('Y-m-d');
?>
Today is Wednesday. To calculate a date in the future you must use the time() function in conjunction with the date() function. time() gives you the current unix time stamp which is the number of seconds since January 1st 1970 (dont quote me on that exact date). To calcuate one week from today you can just calculate the number of seconds in a week and add it to the time function then pass it in as a date() parameter.Code:<?php
echo "Today is " . date('l')
?>
Rather than calculating the number of seconds there is another option for you. Say I want to print yesterdays date using strtotime() in coujunction with date we can accomplish this.Code:<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
echo "Next week will be ";
echo echo date('Y-m-d', $nextWeek);
?>
Similarly you can calculate last monday by doing thisCode:<?php
echo date('d-m-Y', strtotime('-1 days'));
?>
For more information on characters that are recognized in the format parameter string see:Code:<?php
echo date('d-m-Y', strtotime('last monday'));
?>
PHP: date - Manual
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks