Search code examples
phpdatetimedate-arithmetic

How to get different date with the same time


It's maybe a really simple question but I found a little hard since I am still novice on PHP.

Presumably I have:

$time1 = strtotime("today 15:00:00-05:00");

This is just example, $time1 is dynamic at runtime and can be any value, I would like to create new $time2 which has the value:

$time2 = strtotime("this thursday 15:00:00-05:00");

Please note in here $time1 and $time2 have the same 15:00:00-05:00 and only different the day. So, to sump up, I have two inputs:

  1. $time1 which is dynamic at runtime.
  2. the string this thursday.

How to create the $time2 with the value like above.


Solution

  • Find the difference between "today" and "today 15:00:00-05:00" and add it to "this thursday"

    $sometime = "today 15:00:00-05:00";
    $time1 = strtotime($sometime);
    // now find only the hour part
    $time = mktime(0,0,0, date('n', $time1), date('j', $time1), date('Y', $time1));
    $time_difference = $time1 - $time; 
    $time2 = strtotime("this thursday") + $time_difference;
    

    Or even simpler:

    $sometime = "today 15:00:00-05:00";
    $time1 = strtotime($sometime);
    // now find only the hour part
    $hour_string = date('h:i:s', $time1); 
    $time2 = strtotime("this thursday $hour_string");