• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Get an age from dates in PHP/SQL

Joined
Nov 30, 2008
Messages
555 (0.10/day)
Location
Birmingham, England...
Processor Intel Core 2 Quad Q6600 @ 2.8GHz
Motherboard Gigabyte X48T-DQ6
Cooling Zalman 9500 LED CPU Cooler
Memory 2x 2GB Corsair DDR3 XMS3 DHX - 1600MH/PC3-12800
Video Card(s) Gigabyte HD4870 1GB
Storage 2x Seagate 320GB Barracuda (RAID 0) 3x 1TB Samsung F3, 140GB WD Maxtor (10,000rpm)
Display(s) 2x 20" LG Flatron L204WS
Power Supply Powercool 850W
Software Windows 7 Ultimate x64
Hello

I'm looking for an easy way to extract how many days a table entry has been there, from an SQL db into a PHP website.

For example, when the item is inserted, it gets DATE(2013-05-20). I want my session variable to extract that date, then use the current date to determine how many days it's been there. I was thinking something like:

$_SESSION['age'] = new DateTime(date('Y-m-d')) - ("yyyy/mm/dd") - $dbRecord["age"];

but in the example above, this returns -2012 Days

Thanks for you help :)
 

W1zzard

Administrator
Staff member
Joined
May 14, 2004
Messages
27,051 (3.71/day)
Processor Ryzen 7 5700X
Memory 48 GB
Video Card(s) RTX 4080
Storage 2x HDD RAID 1, 3x M.2 NVMe
Display(s) 30" 2560x1600 + 19" 1280x1024
Software Windows 10 64-bit
DATEDIFF() in MySQL

Also look up NOW(), you don't seem to know about it

you could also do it in PHP, I recommend UNIX_TIMESTAMP() in MySQL, so you get the time in a format that PHP likes better than a date string.

PHP function strtotime() is REALLY nice to work with dates, too
 
Joined
Nov 30, 2008
Messages
555 (0.10/day)
Location
Birmingham, England...
Processor Intel Core 2 Quad Q6600 @ 2.8GHz
Motherboard Gigabyte X48T-DQ6
Cooling Zalman 9500 LED CPU Cooler
Memory 2x 2GB Corsair DDR3 XMS3 DHX - 1600MH/PC3-12800
Video Card(s) Gigabyte HD4870 1GB
Storage 2x Seagate 320GB Barracuda (RAID 0) 3x 1TB Samsung F3, 140GB WD Maxtor (10,000rpm)
Display(s) 2x 20" LG Flatron L204WS
Power Supply Powercool 850W
Software Windows 7 Ultimate x64
Thanks for the quick reply :) I'll get reading and report back if I need further help!
 
Joined
Nov 30, 2008
Messages
555 (0.10/day)
Location
Birmingham, England...
Processor Intel Core 2 Quad Q6600 @ 2.8GHz
Motherboard Gigabyte X48T-DQ6
Cooling Zalman 9500 LED CPU Cooler
Memory 2x 2GB Corsair DDR3 XMS3 DHX - 1600MH/PC3-12800
Video Card(s) Gigabyte HD4870 1GB
Storage 2x Seagate 320GB Barracuda (RAID 0) 3x 1TB Samsung F3, 140GB WD Maxtor (10,000rpm)
Display(s) 2x 20" LG Flatron L204WS
Power Supply Powercool 850W
Software Windows 7 Ultimate x64
Worked perfectly using a combination of the two, thanks for the very quick reply w1zzard, appreciate your help

$sql = "SELECT DATEDIFF(now(),age) AS item_age FROM item WHERE item_id = ".$_SESSION['item_id']
 
Top