Ben
Ben

Reputation: 101

Remove 1 week from date in php

Been a long while since I posted here, I have done a LOT of coding without having to ask but I am stuck :(

I have a variable which is called "$date", it is always the current date. Now I have logs which have a date set to them, now what I want to do is delete any logs that are older than a week from the current date. Here's how I'm doing it (? means I don't know what to put).

$date = date('Y-m-d H:i:s');

$one_week_old = $date - ?;

$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < '$one_week_old'");

Upvotes: 0

Views: 1857

Answers (6)

girorme
girorme

Reputation: 361

If you prefer Oriented Object paradigm, we have:

$oneWeekAgo = (new DateTime('-1 week'))->format('d/m/Y');

Explanation:

  • Return a new DateTimeObject
  • Set the timestamp from -1 week
  • Format to your need.

Upvotes: 0

Champion
Champion

Reputation: 11

If you don't need this date information later in PHP, i suggest you to do that directly in the MySql Query. Please consider, that this example will modify just the datepart, not the timepart of the current timestamp. It was't specified exactly if you like to to have whole days deleted or exactly the those data older then 604800 seconds (7 x 24 x 60 x 60 = 604800).

MySQL 5.5 Reference Manual 12.7 Date and Time Functions

mysqli_query($con, "DELETE FROM logs WHERE logs.date < DATE_SUB(NOW(), INTERVAL 1 WEEK)");

Upvotes: 1

user4590533
user4590533

Reputation: 11

$date = date('Y-m-d');
$newdate = strtotime ( '-1 week' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-d' , $newdate );
$query="DELETE FROM logs WHERE logs.date < '".$newdate." 00:00:00 '";
$clearlog = mysqli_query($con,$query);

Upvotes: 1

Secret
Secret

Reputation: 3358

Instead of using another variable, you can just query it directly:

$clearlog = mysqli_query($con,"DELETE FROM logs WHERE logs.date < dateadd(week,-1,getdate()));

Upvotes: 2

Albzi
Albzi

Reputation: 15609

You can do this:

$one_week_old = date("Y-m-d",strtotime("-1 week"));

Upvotes: 1

La3eb
La3eb

Reputation: 27

$one_week_old = date('d-m-Y', strtotime("-1 week"));

Upvotes: 1

Related Questions