Christian
Christian

Reputation: 28124

How can I get the timestamp for a given day of week?

Basically, I have this requirement to convert a present/future weekday to a timestamp.

Example:

today     = Thu, 24 Feb 2010
weekday   = Tue
next date = Tue,  1 Mar 2010
cur stamp = 1267016400
new stamp = 1267448400

Upvotes: 0

Views: 398

Answers (3)

rainmore
rainmore

Reputation: 30

have you tried

strtotime("+7 days", strtotime("Thu, 24 Feb 2010"))

Upvotes: 0

Christian
Christian

Reputation: 28124

This is the code I ended up with:

/**
 * @param $weekday string The weekday in short (3 letter) format, eg: "Mon" or "Tue".
 * @return integer The calculated timestamp.
 */
function next_weekday_to_stamp($weekday,$today=null){
    if(!$today)$today=time();
    $range = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun');
    $days = array_search(date('D'), $range);
    $range = array_slice($range, $days);
    $days = array_search($weekday, $range);
    return strtotime('+'.$days.' days', $today);
}

Talk about over-engineering it out!

Anyway, if someone wants to use this in the past (last weekday), it can be easily adapted.

Upvotes: 0

Long Ears
Long Ears

Reputation: 4896

strtotime('Tue') will return the timestamp of the next Tuesday.

strtotime('Tue', $time) will return the timestamp of the next Tuesday from the given timestamp.

Upvotes: 3

Related Questions