-1

Is there any way to convert "01:10:00" string into the following format "1 h:10 min" using php? I did this way, but I need to do the opposite.

'date('H:i:s',strtotime('1 hour 1 minute 1 second', strtotime('midnight')))'
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • you can explode it on `:` and then you'll have 01, 10, 00 in an array, then just `echo $array[0]. 'h' ` - is the date static or dynamic? – treyBake Jun 26 '17 at 10:58
  • @ThisGuyHasTwoThumbs Yes, I got it and it works, thank you.But.....This is what I did: '$time= "01:10:00"; $each= explode(":", $time); echo $each[0] ."h :" . $each[1]. " min";' // returns 01h :10 min. It's right. The problem is that I didn't want the zeros on right because they aren't required. Can you help me? – Flavio Melo Jun 26 '17 at 11:14

2 Answers2

0

Try this:

$time = '01:10:00';
$date = DateTime::createFromFormat('H:i:s', $time);
echo $date->format('H \h:i \m\i\n');
user1915746
  • 466
  • 4
  • 16
  • Be careful when using date functions for pure times and durations. `DateTime` cannot store incomplete dates so you'll get default values for all what's missing. This can lead to subtle problems involving time zones and DST, or `25:00` wrapping to `01:00 (in case of durations). I'm not saying it cannot be done, but you need to test your code carefully. – Álvaro González Jun 26 '17 at 11:17
0

There're endless ways, e.g.:

$input = '01:10:00';
list($h, $m, $s) = explode(':', $input);
$output = "$h h:$m min";

You can also tweak output format in different ways, e.g.

$output = sprintf("%d h:%02d min", $h, $m);

... will display $h as integer and $m as two-character integer with leading zeroes. It's all just text at this point (don't get confused by the concept of "time").

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • This is what I did: '$time= "01:10:00"; $each= explode(":", $time); echo $each[0] ."h :" . $each[1]. " min";' // returns 01h :10 min. It's right. The problem is that I didn't want the zeros on left because they aren't required. Can you help me? – Flavio Melo Jun 26 '17 at 11:21
  • Sorry. Correction: left zeros @Álvaro González – Flavio Melo Jun 26 '17 at 11:25