PHP converting strtotime into a microtime - php

I'm trying to find a way to make an strtotime with a provided datetime match up somewhat with a time generated from microtime(true).
I can't quite figure it out, I've tried dividing my strtotime by 1000 but this doesn't quite give me the right result, how can I match them up to be identical.
$time = strtotime('2022-04-06 09:00:00') / 1000;
$micro = microtime(true);
echo "$time - $micro";
output
1649260.8 - 1649233311.5081

You can do this just by adding a dot and zeros to your string :
$time = strtotime('2022-04-06 09:00:00');
$micro = microtime(true);
echo $time.".0000 - ".$micro;
Otherwise you can use the number_format function :
$time = strtotime('2022-04-06 09:00:00');
$timemicro = number_format($time, 4, '.', '');
$micro = microtime(true);
echo $timemicro." - ".$micro;
These are the simplest solutions I have found :)

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

Calculating percent of time remaining from two dates

So far im trying to get the percentage of time remaining between two dates so i can use a progress bar..
I have the following code i'm passing in two dates and doing the sum but i am getting an error. i'm not sure if this error is because of the date format if so i can change it.
<?
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
$current = '2015-11-03 16:12:15';
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I am getting the following error.
Warning: Division by zero
strtotime will take a date string and turn it into unix standard time as seconds.
<?
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I would recommend using the DateTime object over strtotime. DateTime allows you to specify the format that creates the timestamp, instead of relying on strtotime to magically figure it out. This makes it far more reliable.
For example:
<?php
$start = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 14:05:15');
$end = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 18:05:15');
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 16:12:15');
$completed = (($current->getTimestamp() - $start->getTimestamp()) / ($end->getTimestamp() - $start->getTimestamp())) * 100;
echo $completed;
?>
Note: DateTime objects were introduced in PHP 5.3. Any older versions will not have DateTime. (and quite honestly, should be updated for many reasons)
You're using strings (basically, plain text)... So you can't calculate anything.
You should use timestamps for that (miliseconds since start of 1970)
http://php.net/manual/fr/function.strtotime.php
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
Those are strings. You can't subtract strings and expect things to work. What's happening is this:
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
Since you're doing -, PHP converts those strings to integers:
$new_start = (int)$start; // 2015
$new_end = (int)$end; // 2015
$new_end - $new_start -> 0
YOu need to strtotime() those values back into a unix timestamp, and then you CAN subtract those values, and get a difference in seconds.

Date is not formatting time correctly PHP

Hello I try to take the difference between two dates and display it.
My problem is that the time difference I get is not the correct one.
This is my code:
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
echo date('H:i', $diffTime);
The result I get is:
02:05
The currect time should be this:
00:05
My guess that the date somehow takes timezone or something like this but Im not sure.
Thanks.
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().
essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.
From the PHP docs:
http://pl1.php.net/strtotime
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
try this
<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
echo round(abs($time1 - $time2) / 60,2). " minute"
?>
Below is the solution of date time in years,days.hours,minutes and seconds.
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;
echo "Minutes - " .$m;
echo "<br/>";

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

How to subtract microtime and display date with milliseconds in php?

How to subtract microtime and display date with milliseconds in php ?
For example: I have set end date and time
$endtime = 2012-02-21 10:29:59;
then I have current date or start date with converted from microtime
$starttime = 2012-02-21 10:27:59.452;
function getTimestamp()
{
$microtime = floatval(substr((string)microtime(), 1, 8));
$rounded = round($microtime, 3);
return date("Y-m-d H:i:s") . substr((string)$rounded, 1, strlen($rounded));
}
echo getTimestamp(); //sample output 2012-02-21 10:27:59.452
Now I want to subtract:
$finaldate = $endtime - $starttime;
I want my output to be like this: 00:00:02.452
You need to use microtime for the start/end values, and only format it for display at the end.
// Get the start time in microseconds, as a float value
$starttime = microtime(true);
/************/
/* Do stuff */
/************/
// Get the difference between start and end in microseconds, as a float value
$diff = microtime(true) - $starttime;
// Break the difference into seconds and microseconds
$sec = intval($diff);
$micro = $diff - $sec;
// Format the result as you want it
// $final will contain something like "00:00:02.452"
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.3f', $micro));
Note: this is returning float values from microtime and using float arithmetic to simplify the math, so your numbers may be extremely slightly off due to the float rounding problem, but you are rounding the result to 3 digits in the end anyway, and minor fluctuations in processor timing are greater than floating point errors anyway, so this is not problem for you on multiple levels.
Well phpmyadmin uses this a code like this to calculate the time that a query took. It's similar to your requirements:
//time before
list($usec, $sec) = explode(' ',microtime($starttime));
$querytime_before = ((float)$usec + (float)$sec);
/* your code */
//time after
list($usec, $sec) = explode(' ',microtime($endtime));
$querytime_after = ((float)$usec + (float)$sec);
$querytime = $querytime_after - $querytime_before;
I think this should work for you. You just have to figure your output format

Categories