Date manipulation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Date manipulation

Post by mjseaden »

Dear All,

I have a date stored in a MySQL database I want to manipulate.

How do I add a year onto a date retrieved from a MySQL database date variable? So if I had 24/04/2004 in the database, how do I add a year to get 24/04/2005?

Or, for example, reduce the date by 28 days, which for the 24/04/2004 example would give 28/03/2004.

Any ideas?

Many thanks

Mark
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post by nigma »

You can convert the mysql date field to a unix timestamp using mktime(). From there it's pretty easy to manipulate days/months/years. Once you've manipulated the timestamp you can convert the timestamp back into a date and insert the new value into the database.

For example:

Code: Select all

// $mysql_date is the date field that you've pulled out of the mysql database
// this splits up $mysql_date so that the year, month and day are each an element in the array $date
$date = explode("/",$mysql_date);

// this converts $mysql_date to a unix timestamp
$timestamp = mktime(0,0,0,$date[0],$date[1],$date[2]);

// this adds one year to the timestamp
$timestamp += 60*60*24*365;

// this converts the timestamp back into a normal date in the form day/month/year
$new_date = date("d/m/Y",$timestamp);
let me know if you need clearification on what I just wrote.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

read through: this for the list of internal date/time functions which could be used to manipulate the dates internally without having to select then update..
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post by nigma »

hey thanks feyd, I didn't know you could do that from mysql.
Post Reply