This question already has answers here:
How to get current time in milliseconds in PHP?
(16 answers)
Closed 7 years ago.
I want to get current timestamp with milliseconds in PHP something like below, in JavaScript I use Date.now()
1436030635348
I tried something like below:
$time = str_replace(".","",microtime(true));
But sometime it is not working properly. Like it prints one or two digits less.
It can print less digits, because it is a float value. So if you get 1234.0005, that `.0005 actually means 500 microseconds. The zeroes after the 5 are lost because it's still an unformatted float value.
The function microtime is based on the system call gettimeofday(), which also isn't accurate to the microsecond. Commonly it's accurate to 10 microseconds. See also Linux - Is gettimeofday() guaranteed to be of microsecond resolution.
-edit- I see the specs in your question have changed from microseconds to milliseconds.
To get the float value you have as an integer, you can multiply by a value. The float value represents seconds. Multiply by 1000 to get milliseconds or 1,000,000 to get microseconds. Since the specs (now) say milliseconds, you should multiply by 1000. 10k will give you accuracy of 1/10ms = 100μs. A millisecond is one thousandth of a second. A microsecond is one millionth of a seconds.
Long story short, to get the time in integer milliseconds, use this:
$milliseconds = intval(microtime(true) * 1000);
Note: there is a reason why you get the time as a string or a float by default. The reason is that on 32 bit systems, PHP's integer is also 32 bits and is not large enough to contain the timestamp including milliseconds and microseconds. So this solution will only work well on a 64 bit system.
$timeStampData = microtime();
list($msec, $sec) = explode(' ', $timeStampData);
$msec = round($msec * 1000);
$result = $sec . $msec;
Something like this
But note, that js date.now() return time in MILLIseconds, not MICROseconds
I think you just need to use this function to get a Timestamp with micro seconds in PHP:
int microtime ( void )
Use it as shown in the following link, following code snippet shows you how I'd altered it according to be helpful to your question:
<?php
function microtime_microseconds()
{
list($usec, $sec) = explode(" ", microtime());
return round(($usec * 1000) + $sec);
}
$micro_time = microtime_microseconds();
echo $micro_time;
?>
And also for reference regarding to that microtime() PHP function, please visit and read this PHP manual page.
Related
I need to calculate the value in Dart/Flutter, as calculated by the gmmktime() function in PHP.
This is what I was trying till now:
var ms = (DateTime.now().toUtc().millisecondsSinceEpoch)/100;
int ms = DateTime.now().toUtc().millisecondsSinceEpoch;
But both of these approaches give a value, which is not expected by this API in its header, here: https://api.kitewalk.com/#authentication
PHP's gmmktime is documented to return "Unix time", which is the number of seconds since the the "Unix epoch".
Your first approach was almost right, but you didn't convert from milliseconds to seconds correctly. There are 1000 milliseconds in a second, so you need to divide by 1000, not 100. Additionally, whatever you're passing the time to probably expects an integral number of seconds and not a floating point value, so you'll need to use integer division or round the quotient afterward.
Also note that the "Unix epoch" is not time-zone dependent; DateTime.millisecondsSinceEpoch already measures against a fixed point in time, so an explicit conversion to UTC isn't necessary (but it doesn't hurt).
A correct version would be:
var unixTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
I am getting some data from some api and I am getting time in following formats/
PT127M
PT95M
which means 127 minutes and 95 minutes respectively.I want to get 127 from this with default functions.Right now I am using shortcut like below
$duration = "PT127M";
$duration = preg_replace("/[^0-9]/","",$duration);
Some one tell me what kind of format is this and if there is any php function available to retrieve the minutes from it.
You can get minutes like this:
$duration = 'PT127M';
$di = new DateInterval($duration);
$minutes = $di->format('%i');
More info here: http://php.net/manual/en/class.dateinterval.php
It might be related to ISO 8601 Duration date format:
To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration (note the time designator, T, that precedes the time value). The smallest value used may also have a decimal fraction, as in "P0.5Y" to indicate half a year. This decimal fraction may be specified with either a comma or a full stop, as in "P0,5Y" or "P0.5Y". The standard does not prohibit date and time values in a duration representation from exceeding their "carry over points" except as noted below. Thus, "PT36H" could be used as well as "P1DT12H" for representing the same duration. But keep in mind that "PT36H" is not the same as "P1DT12H" when switching from or to Daylight saving time.
You can use DateInterval to parse in PHP:
Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.
With this information you can parse your $duration object with this code:
$duration = 'PT127M';
$duration = new DateInterval($duration); // Create a DateInteval Object
echo $duration->format('%i'); // Print minutes from DateInterval Object
I have tried exploding the times, to work with parts before and after the ":" with minimal success. I am receiving both times via XML feed, so I can convert my received strings as necessary, or multiply them by another figure to work with as I need.
$time_1 = "00:59.8408";
$time_2 = "01:00.4734";
$difference = $time_2 - $time_1;
or another way of calculating the difference, should give me back
0.6326
I will be happy to accept any advice. I have attempted subtracting strtotime converted variables, I have as I mentioned above exploded the string with unfavorable results. The, what I believe is, milliseconds have also been an obstacle that I have not worked with in the past.
I appreciate you reading this.
The minus operator in PHP only works with numbers. Your strings will be converted to numbers which then is 1 - 0, so the difference is 1:
$time_1 = "00:59.8408";
$time_2 = "01:00.4734";
$difference = $time_2 - $time_1;
var_dump($difference); # int(1)
Instead write a function that converts the string into seconds as a float like in this example:
/**
* convert time string to seconds
*
* #param string $time %i:%s.%u
* #return float
*/
function time_to_seconds($time) {
sscanf($time, '%d:%f', $minutes, $seconds);
return $minutes * 60 + $seconds;
}
This is pretty straight forward: scan the string first for digits, then the colon and then a float. As the first digits are the minutes, multiply those with 60 and add the seconds as float (one minute is 60 seconds). Return the result (no error checking in there, see sscanf to turn this into production code.
Then do the operation with the results:
$difference_in_seconds = time_to_seconds($time_2) - time_to_seconds($time_1);
var_dump($difference_in_seconds); # double(0.6326)
And that's it. The most important part is that you need to know how to treat the data that is encoded in your string(s) here. Parse the string according to that.
Alright when I do the code:
<script type = "text/javascript" >
document.write((new Date).getTime());
</script>
You get the Unix timestamp in miliseconds. I need something that will match this in PHP. I need a variable to be set to that, NOT necessarily printed. The variable needs to be a string OR number without any formatting (decimals, commas, etc).
The numbers don't have to match exactly, but have to be close. I tried doing time()*1000 but it turns it into scientific notation and I couldn't format it out without messing up the string.
Thanks so much for any help
If you don't need (millisecond) presision, then just divide & Math.floor the javascript's function. So:
time();
and
Math.floor((new Date).getTime()/1000)
should return the same value at the same time.
What you are looking for is millisecond time in PHP. To accomplish this you need to use a combination of the microtime function and some multiplication.
microtime when passed true as its first parameter will return the current time as the number of seconds since the Unix epoch to the nearest microsecond.
To convert the value into an integer value of the number of milliseconds since the Unix epoch you must multiply this value by 1000 and cast to an integer.
So:
$milliseconds = (int)(microtime(true) * 1000);
The javascript
getTime() ;
method returns the number of milliseconds since midnight of January 1, 1970 and the specified date.
A php equivalent is
time() * 1000; // not microtime() as I wrongly said earlier.
However they wont match as php does not support millisecond precision it seems.
With regards to this thread, I've developed a partial solution:
function strtosecs($time,$now=null){
static $LEAPDIFF=86400;
$time=strtotime($time,$now);
return $time-(round((date('Y',$time)-1968)/4)*$LEAPDIFF);
}
The function is supposed to get the number of seconds given a string without checking leap-years.
It does this calculating the number of leap-years 1970 [(year-1986)/4], multiplying it by the difference in seconds between a leap-year and a normal year (which in the end, it's just the number of seconds in a day).
Finally, I simply remove all those excess leap-year seconds from the calculated time. Here's some examples of the inputs/outputs:
// test code
echo strtosecs('+20 years',0).'=>'.(strtosecs('+20 years',0)/31536000);
echo strtosecs('+1 years',0).'=>'.(strtosecs('+1 years',0)/31536000);
// test output
630676800 => 19.998630136986
31471200 => 0.99794520547945
You will probably ask why am I doing a division on the output? It's to test it out; 31536000 is the number of seconds in a year, so that 19.99... should be 20 and 0.99... should be a 1.
Sure, I could round it all and get "correct" answer, but I'm worried about the inaccuracies.
Edit1: Since it doesn't seem obvious, my problem is with inveteracies; you just don't ask PHP for 20 years and it gives you 19.99..., right?
Edit2: It all seems to boil down to the part about 1968;
1970; found it accurate in all tests I've tried.
1969; Found it used here (...ex: (2008-1969)/4 = 9.75...) as well as mentioned here. Accurate after the 2nd year (+3 years) onwards.
1968; as detailed below, this is "year zero" of leap years from unix time (1970). It sounds "right" (to me) but it isn't accurate, at all.
Could this be related to the inherent inaccuracy experienced when using PHP to manage floating point numbers?
http://php.net/manual/en/language.types.float.php
You should replace 1968 in your calculation (where does it come from ?) by the origine of unix time : 1970 and you will get more accurate results.
Edit
You have to do an intval to count the number of leapyears which must be an integer :
return $time - (intval( (date('Y', $time) - 1969) / 4) * $LEAPDIFF);
This will give you correct results within the range +0 -> +68 , end of unix time on 32bit machine