treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Timezone Math

  • So members register a timezone from a HTML select list (values -5, +6.5 and so on), and I am going to do a simple +/- in the timestamp on the page where it is.
    Basically, this is what I came up with (with help from Google, my dear friend):

    <?php
    $timeone = "+10";
    $timetwo = "-4";
    $number = "18:00";

    $exchange = substr($timetwo, 0, 1);
    $therest = substr($timetwo, 1);

    $result = $number. " " .$exchange. " " .$therest;
    $add_em = explode("+", $result);
    $add_em = explode("-", $result);
    echo array_sum($add_em);
    ?>

    Timeone works, but not timetwo. Could anyone try to help me?
  • Your code doesn't know it's a time
    I don't have access to run PHP at the moment but try this:


    <?php
    //3600 = 1 hour
    $time = 18*3600; // 18 for 6PM


    $a = $time + 36000; // +10 hours
    $b = $time - 14400; // -4 Hours

    echo "+10 hours: ";
    print date("G:i",$a);

    echo " -4 hours: ";
    print date("G:i",$b);

    ?>
  • That is my problem, I know but it's because my database prints "+10" and "-5" for users timezone, which I then split up and try to use. Are you sure there aren't any ways I can do that?
  • Well, I guess I can go "if $exchange == '-' then go timestamp - $timetwo"
  • instead of splitting the "+10" and "-5" just multiply the number by 3600?
  • I'm sorry, I don't quite understand. Let's say I have a timestamp that is 18:00 or something GMT+0 or originally, and for people who are American, I want it to be 12:00 or 13:00, now I've got in my database "-6" for that user, how do I use that to make 18:00 go to 12:00?
  • This is a little hacky, but should do the trick
    <?php
    $timeStamp = "18:00";
    $timeDifference = "-5.5"; // From your Database
    $timeInt = (floatval(str_replace(":",".",$timeStamp)) * 3600) + (floatval($timeDifference) * 3600);

    echo date("G:i",$timeInt);
  • Amazing! Thank you so much @karlpcrowley ! :)
  • No problem, if you edit your first post you can mark this as solved