3

Possible Duplicate:
Convert seconds into days, hours, minutes, seconds in PHP
How to convert a decimal into time, eg. HH:MM:SS

what I am doing here is I am saving posts time as UTC in mysql, after retrieving the time stamp from sql I am using strtotime() to convert it into seconds, and then am adding offset time to these seconds to show current local time. Now the question here is when I try to reconvert these seconds into hours, say for example

$seconds = 330*60 //Thats 5.30 hours and 60 seconds gives me 19800 as an output

now when I reconvert it back to hours its showing me 5.50 instead of 5.30

sprintf ("%.2f", 19800/60/60); //Output of 5.50 instead I want is 5.30 

I know it's a mathematical expression am doing wrong, any help would be appreciated with a clean explanation.

Community
  • 1
  • 1
Random Guy
  • 2,878
  • 5
  • 20
  • 32
  • But [330 minutes to hours](http://www.wolframalpha.com/input/?i=330+minutes+to+hours) ?? 5 hours 30 minutes != 5.30 hours – sachleen Sep 04 '12 at 18:31
  • 1
    if you set the proper timezone in your script, you shouldnt need to do that conversion at all – Gordon Sep 04 '12 at 18:32
  • I want the output as 5.30 and not 5.50 – Random Guy Sep 04 '12 at 18:34
  • @Gordon I just want to show that 19800 is +5.30 offset at front .. I know I don't need it in my code functioning as I just add these to `strtotime()` and use `date()` to show local time – Random Guy Sep 04 '12 at 18:35
  • @RandomGuy I'm trying to understand your question. Mathematically `19800/60/60 = 5.50` Where do you get 5.30? – sachleen Sep 04 '12 at 18:38
  • 1
    5 and a half hours, 5 hours and 30 minutes – Mihai Iorga Sep 04 '12 at 18:38
  • @sachleen Ya I know mathematically it is 5.50 but what if I want to convert it to 5.30?and for you guys out here I am using simple `date_default_timezone_set("UTC");` and I guess this has nothing to do with my question... – Random Guy Sep 04 '12 at 18:40
  • 1
    Oh I get it. Then you can just `time = 5.5; hours = (int)time; minutes=(time-hours)*60` – sachleen Sep 04 '12 at 18:41
  • @sachleen that's right expression.. – Random Guy Sep 04 '12 at 18:43
  • [This answer](http://stackoverflow.com/a/8273826/24950) from the thread I linked to will help. – Robert K Sep 04 '12 at 19:13
  • I still dont get why you calculate that instead of using date('P') on your regular timestamp in that timezone. – Gordon Sep 04 '12 at 19:17
  • @Gordon I am using this nowhere in my code functioning, I am just using this to ouput a user at what offset he is at.. – Random Guy Sep 04 '12 at 19:18

1 Answers1

0

Not the most elegant solution but this works:

$original = (19800 / 60 / 60);
$hours = floor($original);
$minutes = ($original - $hours) * 60;

Or this is probably better using modulus:

$hours = floor(19800 / 60 / 60);
$minutes = (19800 / 60) % 60;
Pitchinnate
  • 7,517
  • 1
  • 20
  • 37