Get Time Ticks in PHP - php

Consider this line of code in C#
ordernumber.Value = DateTime.Now.Ticks.ToString();
How to get same ordernumber.Value in PHP
$ordernumberValue = microtime(); //?
I try to this
echo microtime(true) * 10000000;
But get result string.length was difference.
short length than C#.

From .NET documentation:
DateTime.Ticks Property
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar), which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
In PHP this is implemented simply as time():
time
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
microtime() similarly returns time in seconds and microseconds after decimal point, so it has greater precision. For some archaic reasons, the default value is a string, but if you pass true as first argument, you'll get a nice float:
rr-#burza:~$ php -r 'echo microtime(true);'
1434193280.3929%
So all you have to do is to scale the value returned by either time() or microtime() by a constant factor.
According to Wikipedia, a nanosecond is equal to 1000 picoseconds or 1⁄1000 microsecond, or 1/1000000000 second. So 100 nanoseconds would mean 100/1000000000 microseconds, i.e. one .NET tick = 1/10000000 second, i.e. one second = 10000000 .NET ticks. Thus you need to multiply value returned by time() or microtime() by 10000000 like this:
microtime(true) * 10000000

One tick is 1/10000000 of second.
This code converts current microtime to "ticks" count:
list($usec, $sec) = explode(" ", microtime());
$ticks = (int)($sec*10000000+$usec*10000000);

I am not sure if this is what you are looking :-
$mt = microtime(true);
$mt = $mt*1000; //microsecs
$ticks = (string)$mt*10; //100 Nanosecs
echo $ticks; //14341946614384
Now the major difference is Ticks is 100-Nanoseconds since 12:00:00 midnight, January 1, 0001 while this will produce 100-Nanoseconds since January 1 1970

Related

PHP get UTC/GMT time, round to nearest minute, and format to yyyyMMddHHmm

I'm generating a UTC/GMT date with PHP that needs to be in the format yyyyMMddHHmm and needs to be rounded to the nearest minute.
For example, January 3rd, 2020 13:28:56 needs to be 202001031329 and it needs to be rounded to the nearest minute. (30 seconds or greater rounds up, otherwise round down)
For example:
<?php
/*
Start with the UTC/GMT time -- January 3rd, 2020 13:28:56
Round to the nearest minute -- January 3rd, 2020 13:29:00
Convert to format yyyyMMddHHmm -- 202001031329
*/
$date = gmdate("YmdHi", time());
// Need to round to the nearest minute (30 seconds or greater rounds up, otherwise round down)
echo $date;
?>
So far I've figured out how to get the current date with the gmdate() and put it in the right format. However, I'm not sure how to round to the nearest minute.
I suggest you use a DateTime object instead. Handling dates (and times) can be very difficult if you want to do it correctly, and PHP already makes it pretty easy for you this way.
Then, just add one minute if the "seconds hand" is at least at 30:
$dateTime = new DateTime();
$dateTime->setTimezone(new DateTimeZone('UTC'));
echo 'Debug date: ' . $dateTime->format('Y-m-d H:i:s') . PHP_EOL;
echo 'Rounded to minute: ';
if ($dateTime->format("s") >= 30) {
$dateTime->add(new DateInterval('PT1M')); // adds one minute to current time
}
echo $dateTime->format("YmdHi") . PHP_EOL;
Example outputs:
Debug date: 2021-03-18 23:57:25
Rounded to minute: 202103182357
Debug date: 2021-03-18 23:57:38
Rounded to minute: 202103182358
Debug date: 2021-03-18 23:59:34
Rounded to minute: 202103190000
This also takes care of overlapping days and such (see last example above), which fiddling around with the raw numbers would not - or at least it would get very complicated that way.
The result of time() will be in seconds. If you want to round up, you could simply add 30 seconds to it, then take the relevant parts in the format:
$date = gmdate("YmdHi", time() + 30);
echo $date;

how to increase an integer every specific minute in php

I need a php code that when you type (time), and a (base number), it increases by base number value, on specific time intervals.
e.g:
every 40 minutes, add 0.0001 to the base number 0.04
0.04
0.0401
0.0402
.....
You can use the unixtime and calculate how many 40 minutes that has elapsed.
$start = 1537088883; //Unix time of when I started writing answer.
$elapsed = time() - $start; // elapsed seconds since start
$counts = floor($elapsed/(60*40)); // number of 40 minutes that has elapsed
echo 0.04 + (0.0001*$counts);
https://3v4l.org/q9Vhm
Right now it will output just 0.04, but if we manipulate the $start we will get a different output ( or just wait 40 minutes and the same code will output a different number).
https://3v4l.org/E9XWN
If you want to set a start date and time you can use strtotime to convert a human readable date to Unix time.
$start = strtotime("2018-09-01 09:00:00");
https://3v4l.org/c6g0l

PHP getting weekdays, hours and minutes

What's wrong with my code? I want my script to check if it is Monday and is greater or equal to 22:00 and less than or equal to 23:00.
$t = date("D:G:i");
if ($t >= "Mon:22:00" && $t <= "Mon:23:00") {
$status = "up";
} else {
$status = "down";
}
you cannot compare strings (it is not dates, it is just strings of arbitrary symbols), as we're not code-writing monkeys I'll just describe how you should do it instead of providing copy-pastable code:
get weekday number, hour, minute from current time into 3 separate variables
compare weekday variable with monday value
if weekdays are ok - compare hours with 22
minutes can be omitted here, if you check for [22, 23), or you need to make additional comparison for 23:00 case
another approach - generate unix timestamps for the closest monday 22 and 23 hours, and then numeric comparisons
You're comparing two strings instead of two numerical values. Not ideal at all. You want to look into converting the dates into a Unix timestamp and comparing those values.
mktime: http://php.net/manual/en/function.mktime.php
mktime will allow you to get a Unix timestamp for any date.
time: http://php.net/manual/en/function.time.php
time will give you the current date and time as a Unix timestamp.
You can then compare to find out which is larger/smaller than the other.

PHP calculating time difference, result 1 hour wrong

I want to calculate difference of two times and print it in pretty way. I know the difference will never exceed 24 hours, so I tried the following
$time = 7200; //time difference in seconds
date("H:i:s", $time); // should print 02:00
The result is unexpected, it prints 03:00 instead.
What am I doing wrong?
Why not the DateTime::diff??
Here, check PHP.net for DateTime class
Grabbed from php.net datetime diff page:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
//Outputs +2 days
The PHP date() function is meant for formatting absolute time stamps (as in "Friday, 20 July 2012, 15:02 UTC"), not for time differences (as in "3 hours and 5 minutes ago").
In some cases, it is possible to trick date() into producing something that looks like a correctly formatted time difference by setting your time zone to UTC and relying on the fact that the Unix epoch happens to fall on midnight in UTC. However, even then, this will only work for positive time differences of less than 24 hours.
Instead, the correct solution is to use a function designed for formatting time differences, or write one yourself. Here's a simple function to do so:
function format_time_difference ( $delta ) {
$sign = ( $delta < 0 ? "-" : "" );
$delta = abs( $delta );
return sprintf( "%s%02d:%02d:%02d", $sign, $delta / 3600,
($delta / 60) % 60, $delta % 60 );
}
Of course, you can extend this function to e.g. include days in the output if you like.
You should never use date to compute time difference. Firstly it is ugly hack. It was not intended for that purpose. And secondly, it works reliably only when timezone set to UTC.
Now, why it does not work:
PHP function date takes two arguments, format and timestamp, the latter is defined as number of seconds from 1st January 1970 00:00 UTC called unix epoch. So if you call date("H:i", 3600) and your timezone is set to UTC, it will return "01:00", cause it represents time one hour after unix epoch and the epoch was at the midnight.
The problem is, unix epoch was at the midnight only in UTC, not in the other timezones. And this is the source of the incorrect result.

Microseconds unix time integer as a string in PHP

I need the current unixtime as a round number of microseconds in a string. There's a chance the code could run on a machine with 32 bit integers so I'd beter avoid ints. The value is used only in SQL queries, so a string will be fine.
Is it safe to use the following code?
$x = explode(' ', microtime());
$y = $x[1] . substr($x[0], 2, 6);
Is it safe to assume the coordinates of these substrings in microtime()'s return value are invariant?
Is it safe to assume the coordinates of these substrings in microtime()'s return value are invariant?
Yes it is, pretty much. The string return value is there since longer time an preserved. One proposed change is to make the optional argument defaulting true, however, then you can set it to false to get the string.
It's documented as such in the PHP manual, so as long as you trust that PHP won't starting breaking backward compatibility any time soon, then yes, you can trust this.
By default, microtime() returns a string in the form "msec sec", where sec is the current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec expressed in seconds.
If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
Edit nevermind, I misunderstood.

Categories