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.

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

So, concrete example would be, strtotime('last friday') and then subtract 86400 * 7 (86400 seconds times 7 days).
@jishi indeed, or really everything listed under examples at the given php.net link :D
@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.
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).')';  
    }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.