-1

How can I get 24-hour format date (hours and minutes) from milliseconds?

I got this milliseconds value: 1433630097855

I want it to print out the time in hours/minutes. I can't remember exactly what time that was, but I think it's around 00:45

So it should print out like: 00:45

If it was 3 o'clock in afternoon, it should print out something like: 15:25

I couldn't find this conversion for 24h format and when it's 00:xx i tried some but it prints out just "0"

Like:

0:10

I want it like 00: in beginning.

Is there perhaps a quick command for this already in php or do i need some function?

TyhaiMahy
  • 85
  • 1
  • 2
  • 8
  • PHP's [DateTime](http://php.net/manual/en/datetime.format.php) offers a whole range of date & time formatting options –  Jun 06 '15 at 22:43
  • You should see thoses threads : - http://stackoverflow.com/questions/557959/php-convert-milliseconds-to-date - http://stackoverflow.com/questions/17909871/getting-date-format-m-d-y-his-u-from-milliseconds – Akimoto Jun 06 '15 at 22:45
  • Assuming that it's milliseconds from 1-1-1970 00:00:00 GMT, `$var = DateTime::createFromFormat('U', intval(1433630097855 / 1000)); echo $var->format('H:i:s');` gives `22:34:57` today – Mark Baker Jun 06 '15 at 22:59
  • Thats what Im trying to fix. Right now it's 01:19 CEST here. It gives me 13:19 for some reason when I use that code @MarkBaker – TyhaiMahy Jun 06 '15 at 23:19
  • Well a Unix timestamp should be UTC, so you need to set the timezone for the DateTime object to your local time: `$var = DateTime::createFromFormat('U', intval(1433630097855 / 1000)); $var->setTimezone(new DateTimeZone('Europe/Copenhagen')); echo $var->format('H:i:s');` – Mark Baker Jun 06 '15 at 23:36

2 Answers2

2

Convert miliseconds to seconds 1433630097855 / 1000 and then just use seconds (integer timestamp) in datetime functions that you are familiar with. And don't forget about the timezone.

$ms = 1433630097855;
$s = floor($ms/1000);
echo date('H:i:s', $s); # 22:34:57

demo

If you wish the output for other timezone, set it:

date_default_timezone_set('America/Los_Angeles');
echo date('H:i:s', $s); # 15:34:57

demo

You can even use DateTime class, like:

$dt = new DateTime("@$s");
$dt->setTimeZone(new DateTimeZone('America/Los_Angeles'));
echo $dt->format('H:i:s'); # 15:34:57

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107
0

You can use create a new date object form the timestamp

http://php.net/manual/en/function.date.php

Jon Bates
  • 3,055
  • 2
  • 30
  • 48