Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Subtract 30 days to a date

Status
Not open for further replies.

storm197

MIS
Oct 9, 2002
55
CA
Hi,

I want to do a thing I thought would be simple.

I have a date, example : 2004-10-15 11:17:42

I want to subtract 30 days from it (a month)

Result I want: 2004-09-15 11:17:42

Can anyone help me? I tried to use the mktime function, but it gives me a result like 1097899200
 
Code:
$date = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")));

*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
Here's another way:
Code:
<?
$date = '2004-10-15 11:17:42';
echo date('Y-m-d g:i:s a',strtotime("-30 days"))."\n"; //Thirty days before 'now'
echo date('Y-m-d g:i:s a',strtotime("-30 days",strtotime($date)))."\n"; //Thirty days before the given date
?>

Ken
 
Ahh, great question!

To be sure, maybe I should re-post as this:

Code:
$date = date("Y-m-d", mktime(0, 0, 0, date("m") < 1 ? 12 : date("m") - 1, date("d"), date("Y")));

or, neater, but one more line of code:

Code:
$m = date("m") < 1 ? 12 : date("m") - 1;
$date = date("Y-m-d", mktime(0, 0, 0, $m, date("d"), date("Y")));

Thanks for pointing that out [blue]eb[/blue].

*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
I believe the cLFlaVA would work and give you the right year (instead of giving some funny 0th month, it would update the year and the month), I will check again...just a thought

Flub
 
I actually make MySQL do all my date calculations, even if I don't use the database for storage.

Oracle has a nice little convention of always having a table called 'dual' that has one row with one column in it. It allows you to write queries like "select username from dual" or "select sysdate from dual". Both username and sysdate are pseudo-columns.

I create the same thing in a database in mysql and grant select to a user with no password, so I can do "select date_sub( now(), interval 30 day) from dual" and I always get one row returned.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top