4

Suppose i know that today's day is monday. How do i use mktime() in php to get unix timestamp for last friday and the friday before that??

suppose today's date is 17-01-2011 and its a monday. Then i want the timestamp for 14-01-2011 00:00:00 and 7-01-2011 00:00:00.

ayush
  • 14,350
  • 11
  • 53
  • 100
  • *(reference)* [Supported Date and Time Formats](http://de2.php.net/manual/en/datetime.formats.php) and more specifically [Relative Formats](http://de2.php.net/manual/en/datetime.formats.relative.php) – Gordon Jan 17 '11 at 08:50

3 Answers3

8

check out strtotime http://php.net/manual/en/function.strtotime.php ..solves most of that kinda issues - otherwise you must strap the date yourself

Hannes
  • 8,147
  • 4
  • 33
  • 51
  • 1
    So, concrete example would be, strtotime('last friday') and then subtract 86400 * 7 (86400 seconds times 7 days). – jishi Jan 17 '11 at 09:08
  • @jishi indeed, or really everything listed under examples at the given php.net link :D – Hannes Jan 17 '11 at 09:10
  • 1
    @yishi substracting hardcoded seconds from timestamps will lead to wrong results when there is DST shifts. strtotime is DST aware, so just use the relative formats as given in the link below your question. – Gordon Jan 17 '11 at 09:32
1

A lot more simpler than you thought (or even I for that matter)! Essentially, strtotime("last friday", time()) gets the timestamp of... last friday!

Getting the current timestamp first:

$unixNow = time();
echo date('r', $unixNow) . "<br />";
//Thu, 10 Jan 2013 15:14:19 +0000

Getting last friday:

$unixLastFriday = strtotime("last friday", $unixNow);
echo date('r', $unixLastFriday) . "<br />";
//Fri, 04 Jan 2013 00:00:00 +0000

Getting the friday before that:

$unixFridayBeforeThat = strtotime("last friday", $unixLastFriday);
echo date('r', $unixFridayBeforeThat) . "<br />";
//Fri, 28 Dec 2012 00:00:00 +0000
Florian Mertens
  • 2,418
  • 4
  • 27
  • 37
1

Something like this should do

<?php
    // Check if today is a Monday
    if (date('N') == 1)
    {
        // Create timestamp for today at 00:00:00
        $today = mktime('0', '0', '0', date('n'), date('j'), date('Y'));

        $last_friday = $today - 60*60*24*3;
        $last_last_friday = $today - 60*60*24*10;

        // Convert to a readable format as a check
        echo 'Last Friday\'s timestamp is ' . $last_friday . ' (' . strftime('%d-%m-%Y %H:%M:%S', $last_friday).') <br />';  
        echo 'Last last Friday\'s timestamp is ' . $last_last_friday . ' (' . strftime('%d-%m-%Y %H:%M:%S', $last_last_friday).')';  
    }
joelcox
  • 562
  • 9
  • 19