Sherwin Flight
Sherwin Flight

Reputation: 2363

Get timestamps for beginning and end of last seven days

I am trying to output this in PHP as a UNIX timestamp instead:

05-30-2014 0:00:00
05-30-2014 23:59:59
05-29-2014 0:00:00
05-29-2014 23:59:59
05-28-2014 0:00:00
05-28-2014 23:59:59
05-27-2014 0:00:00
05-27-2014 23:59:59
05-26-2014 0:00:00
05-26-2014 23:59:59
05-25-2014 0:00:00
05-25-2014 23:59:59
05-24-2014 0:00:00
05-24-2014 23:59:59

This should be dynamic, and always show the previous seven days.

So, I am trying to get the start, and end, of each of the last seven days as a timestamp.

I was able to get the dates to output, but when including times and converting to timestamps I think it is getting messed up.

EDIT

I have this so far, which gets me the correct starting date and times, but this needs to be converted to a timestamp.

$timestamp = time()- 3600 * 24;
for ($i = 0 ; $i < 7 ; $i++) {
    echo date('Y-m-d 00:00:00', $timestamp) .'<br />';
    echo date('Y-m-d 23:59:59', $timestamp) .'<br />';  
    $timestamp -= 24 * 3600;
}

When I try changing it to a timestamp, and then use an online converter to reverse the timestamp it's always off by 5 hours. For example, I took the timestamp for midnight of a given date, and checked it in the online converter to see if it was correct, but it was saying 5am instead of midnight.

Upvotes: 1

Views: 598

Answers (2)

nl-x
nl-x

Reputation: 11832

$date = new DateTime();
for($i = 0; $i < 7; $i++) {
    $date->modify("last day");
    $date->setTime(0,0,0);
    echo $date->getTimestamp() . "<br/>\n";
    $date->setTime(23,59,59);
    echo = $date->getTimestamp() . "<br/>\n";
}

edit

If you want to have a specific timezone anyway, then change my first line above into:

    $date  = new DateTime("now", new DateTimeZone("Europe/Amsterdam"));

And set your desired timezone in stead of Europe/Amsterdam.

edit 2

Your own code that you have put in your own edit isn't that bad. You just needed to add strtotime() to turn your date string into a timestamp:

$timestamp = time()- 3600 * 24;
for ($i = 0 ; $i < 7 ; $i++) {
    echo strtotime(date('Y-m-d 00:00:00', $timestamp)) .'<br />';
    echo strtotime(date('Y-m-d 23:59:59', $timestamp)) .'<br />';  
    $timestamp -= 24 * 3600;
}

And don't be scared of what an online converter says. The online converter could be in a different timezone.

Upvotes: 2

bmacuer
bmacuer

Reputation: 37

$start_timestamp = mktime(0, 0, 0, date("m"), date("d"), date("y"));

$end_timestamp = $start_timestamp+86399;

//run it 7 times
for ($x=0; $x<7; $x++) {
    $start_timestamp = (int) $start_timestamp - 86400;
    $end_timestamp = $start_timestamp+86399;

    echo $end_timestamp."<br />".$start_timestamp."<br />";
} 

Upvotes: 0

Related Questions