Time conversion using php - php

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')))'

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").

Try this:
$time = '01:10:00';
$date = DateTime::createFromFormat('H:i:s', $time);
echo $date->format('H \h:i \m\i\n');

Related

Format unformatted time number to readable 24 hour time

My client has entered some start and end dates into our system and I want to be able to format it with PHP.
The values are 930 and 1530. Processing the 1530 variable is fine but its the 930 that returns false.
Here is my script so far but no success. Error returns bool(false) because it can't get a readable time (I believe?)
$time = DateTime::createFromFormat('Hi', $var);
$format = "H:i";
$result = $time->format($format);
That's because your initial time format is ambiguous. Assuming that you have time without leading zeros all the time one can do something like this:
$var = '930';
$time = DateTime::createFromFormat('Hi', str_pad($var, 4, '0', STR_PAD_LEFT));
$format = "H:i";
$result = $time->format($format);
I wouldn't bother with DateTime for this, split it and join it like this:
$var = 1530;
$minutes = substr($var, -2, 2);
$hours = str_replace($minutes, '', $var);
$time = $hours . ':' . $minutes;
Then use DateTime on the string:
$dateTime = new DateTime($time);
$time = $dateTime->format('H:i');

PHP: Split unix timestamp range into 5 chuncks

I have a requirement where I need to extract 5 points from a Unix time stamp or PHP time stamp range.
For Example,
From 2014-06-26 07:53:26 to 2014-06-27 07:52:46.
I need five points from these two dates in exact or approximate intervals, to chart using pChart.
Currently My Code is
$diff = $mintime->diff($maxtime);
$range = max($timestamps) - min($timestamps);
$cnt = count($timestamps);
$temp = ceil($range * (20/100));
for($i=0;$i<$cnt;$i++)
{
if($i%($cnt/5) == 0)
$point[$i] = gmdate("Y-m-d H:i:s",min($timestamps) + $temp * ($i+1));
else
$point[$i] = null;
}
But My Code returns erratic values. I know the problem is with the temp variable. Help me solve this.
Thanks
Try this:
$from = '2014-06-26 07:53:26';
$to = '2014-06-27 07:52:46';
$diff_stamp = strtotime($to) - strtotime($from);
$range = range(strtotime($from), strtotime($to), $diff_stamp/4);
Here, $range is an array of timestamps. To convert each back to a date, you could use array_map:
$range = array_map(function($a){return date('Y-m-d H:i:s', $a);}, $range);
See Demo Updated
Resources:
strtotime(), range(), array_map()
$splitter=($timestamp1-$timestamp2);
$timestamp_between=array();
for($i=0;$i<5;$i++) $timestamp_between[]=$timestamp1+($i*$splitter);
print_r($timestamp_between);

exploding a timestamp and adding : every 2 places

I have a PHP Script that has an INT in the format MMSSMS - Minutes Seconds Milliseconds defined as $time. I just need a : every 2 places in $time. Any help is appreciated.
Example: $message = 'I clocked in (MM:SS:MS) '.$time.';
the issue is the $time displays as 000044 instead 00:00:44 on echo
This code replaces 2 consecutive digits not on the end of the string with the digits followed by colon
$message = 'I clocked in (MM:SS:MS) '.preg_replace('/\d{2}(?!$)/','$0:',$time);
php.net/preg_replace
demo: http://sandbox.onlinephpfunctions.com/code/de0ce1e4466ff747f1bba2ac92331623a1b234ed
<?php
$time = '123456';
$str = strval($v);
$time = $str[0].$str[1].":".$str[2].$str[3].":".$str[4].$str[5];
echo $time;
?>
Hope this helps:
$time = '001122';
$minutes = substr("$time", 0, 2);
$seconds = substr("$time", 2, 2);
$mills = substr("$time", 4, 2);
echo $newTime = "$minutes:$seconds:$mills";
You can use chunk_split() in conjunction with rtrim()
$time = '000044';
$time = rtrim(chunk_split($time, 2, ':'), ':');
Edit
If $time is an INT, you would need to convert using (string)$time or strval($time). However, in your example you are using 000044, so I am assuming $time is already a string...

How to convert 00:03:30 in 3m30s

I search for my problem on php.net and on stackoverflow and I did'nt find a good answer to solve my problem, so I decide to ask it !
I have a number of secs :
210
I transform it to 00:03:30 :
gmdate('H:i:s', 210);
But how can I format my answer like :
3m30s or 3min30secs ?
I think I can make this transformation by Exploding my results and concatenate with variable, but I don't know if it's the best solution...
$part = explode(":", $mytime);
$hours = $part[0];
$mins = $part[1];
$secs = $part[2];
$hoursvar = "h";
$minsvar = "m";
$secsvar = "s";
$timefinal = $hours.$hoursvar.$mins.$minsvar.$secs.$secsvar;
Can anyone help me? Thanks.
echo ltrim(date("H", 210), "0")." hours, ".
ltrim(date('i', 210), "0")." min, ".
ltrim(date('s', 210), "0")." secs";
You can format the string inside gmdate, just escape the characters you want to print:
$sec = 210;
echo gmdate("i\m s\s", $sec);
Output:
03m 30s
date() works a little bit like printf(). You pass a format string containing a defined set of meta characters which will be replaced by values. Note that the format string can contain any content not just meta characters. The manual page explains this as well. You can use:
date('i\ms', 210);
You see that you have to escape literals (the m) to that they were not replaced by values.
I hope you can live with a leading zero : 03m30
if not, use:
$date = date('i\ms', 210);
if(strpos($date, '0') === 0) {
$date = substr($date, -strlen($date) + 1);
}
Or, shorter, thanks #Orangepill :) :
$date = ltrim(date('i\ms', 210), '0');
as there is no meta character for minutes without leading zeros known by date().
This is easy, your current date format is H:i:s and you want to convert it to i:s
So you do the following
$date = "00:03:30";
$new_date = date("i_s-",strtotime($date));
Since we can't insert the letters m and s in the function we can use str_replace to replace the _ with m and replace - with s so
$new_date = str_replace("_","m",$new_date);
$new_date = str_replace("-","s",$new_date);
That was the best way I could think of.
$string_time = '00:03:30';
$int_time = strtotime(date('Y-m-d').' '.$string_time);
echo date('i', $int_time).'m'.date('s', $int_time).'s';
$seconds = 210;
$date = gmdate("H\h:i\m:s\s", $seconds);
echo preg_replace('/0([0-9])/','$1', $date);
OUTPUT
0h:3m:30s
You can use gmdate with preg_replace to remove 0 from begining.
OR more advanced
$seconds = 210;
$date = gmdate("H\h:i\m:s\s", $seconds);
$match = array('/0([0-9])/','/s/','/m\:/','/h\:/');
$replace = array('$1', ' sec ', ' min ', ' hours ');
echo preg_replace($match,$replace, $date);
OUTPUT:
0 hours 3 min 30 sec
echo ltrim(date("H", 210), "0")." hours, ".
ltrim(date('i', 210), "0")." min, ".
ltrim(date('s', 210), "0")." secs";
Thanks to Orangepill !

How to convert microtime() to HH:MM:SS:UU

I was measuring some curl requests and I used microtime(true). The example output would be 3.1745569706
This is 3.1745569706 seconds. I want to convert that to a somewhat more readable format, let's say 00:00:03:17455 (HOURS:MINUTES:SECONDS:MILLISECONDS)
$maxWaitTime = '3.1745569706';
echo gmdate("H:i:s.u", $maxWaitTime);
// which returns
00:00:01.000000
echo date("H:i:s.u" , $maxWaitTime)
// which returns
18:00:01.000000
That looks wrong. I'm not quite sure what I'm missing here.
How do I convert microtime() to HH:MM:SS:UU ?
From the PHP.net article on date() which is similar to gmdate(), except that the time is returned in GMT:
Since this function only accepts integer timestamps the u format
character is only useful when using the date_format() function with
user based timestamps created with date_create().
Use something like this instead:
list($usec, $sec) = explode(' ', microtime()); //split the microtime on space
//with two tokens $usec and $sec
$usec = str_replace("0.", ".", $usec); //remove the leading '0.' from usec
print date('H:i:s', $sec) . $usec; //appends the decimal portion of seconds
Which prints: 00:00:03.1745569706
If you want you can use round() to round the $usec var even more.
If you use microtime(true) use this instead:
list($sec, $usec) = explode('.', microtime(true)); //split the microtime on .
<?php
function format_period($seconds_input)
{
$hours = (int)($minutes = (int)($seconds = (int)($milliseconds = (int)($seconds_input * 1000)) / 1000) / 60) / 60;
return $hours.':'.($minutes%60).':'.($seconds%60).(($milliseconds===0)?'':'.'.rtrim($milliseconds%1000, '0'));
}
echo format_period(3.1745569706);
OUTPUT
0:0:3.174
Assuming one really cares about microseconds, which is admittedly rare, then one should not use any representation that involves floats.
Instead use gettimeofday() which will return an associative array that contains the seconds and microseconds as integers.
$g1 = gettimeofday();
# execute your process here
$g2 = gettimeofday();
$borrow = $g2['usec'] < $g1['usec'] ;
$seconds = $g2['sec'] - $g1['sec'] - $borrow ;
$micros = $borrow*1000000 + $g2['usec'] - $g1['usec'] ;
$delta = gmdate( 'H:i:s.', $seconds ).sprintf( '%06d', $micros );

Categories