In Actionscript, the Unix timestamp in milliseconds is obtainable like this:
public static function getTimeStamp():uint
{
var now:Date = new Date();
return now.getTime();
}
The doc clearly states the following:
getTime():Number Returns the number of
milliseconds since midnight January 1,
1970, universal time, for a Date
object.
When I trace it, it returns the following:
824655597
So, 824655597 / 1000 / 60 / 60 / 24 / 365 = 0.02 years.
This is obviously not correct, as it should be around 39 years.
Question #1: What's wrong here?
Now, onto the PHP part: I'm trying to get the timestamp in milliseconds there as well. The microtime() function returns either a string (0.29207800 1246365903) or a float (1246365134.01), depending on the given argument. Because I thought timestamps were easy, I was going to do this myself. But now that I have tried and noticed this float, and combine that with my problems in Actionscript I really have no clue.
Question #2: how should I make it returns the amount of milliseconds in a Unix timestamp?
Timestamps should be so easy, I'm probably missing something.. sorry about that. Thanks in advance.
EDIT1: Answered the first question by myself. See below.
EDIT2: Answered second question by myself as well. See below. Can't accept answer within 48 hours.
I used unsigned integer as the return type of the function. This should be Number.
public static function getTimeStamp():Number
{
var now:Date = new Date();
return now.getTime();
}
Think I got the function for getting milliseconds in PHP5 now.
function msTimeStamp() {
return round(microtime(1) * 1000);
}
For actionscript3, new Date().getTime() should work.
In PHP you can simply call time() to get the time passed since January 1 1970 00:00:00 GMT in seconds. If you want milliseconds just do (time()*1000).
If you use microtime() multiply the second part with 1000 to get milliseconds. Multiply the first part with 1000 to get the milliseconds and round that. Then add the two numbers together. Voilá.
Use this:
intval(microtime(true)*1000)
To normalize a timestamp as an integer with milliseconds between Javascript, Actionscript, and PHP
Javascript / Actionscript:
function getTimestamp(){
var d = new Date();
return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()).valueOf();
}
PHP:
function getTimestamp(){
$seconds = microtime(true); // true = float, false = weirdo "0.2342 123456" format
return round( ($seconds * 1000) );
}
See PHP note at "ben at sixg dot com's" comment at: http://www.php.net/manual/en/function.gmmktime.php
EXCERPT:
For most intents and purposes you can imagine that mktime() first converts your input parameters to GMT and then calls gmmktime() which produces a GMT timestamp.
So, time() always will return the same thing at the same actual moment, anywhere in the world.
gmmktime() and mktime(), when given specific time parameters, convert those time parameters FROM the appropriate timezone (GMT for gmmktime(), local time for mktime()), before computing the appropriate timestamp.
UPDATE:
On some versions of PHP, the timestamp with milliseconds is too large to display as a string. So use the sprintf function to get the string value:
PHP
function getTimestamp($asString=false){
$seconds = microtime(true); // false = int, true = float
$stamp = round($seconds * 1000);
if($asString == true){
return sprintf('%.0f', $stamp);
} else {
return $stamp;
}
}
microtime() in php5 returns unix timestamp with microseconds as per microtime() and if the get_as_float argument is not provided, it gives you a string formatted as "msec sec" so the first part is the millisecond part and the second is the second part. Just split it in two and you get the two parts of the timestamp
Simple answer for PHP:
function exact_time() {
$t = explode(' ',microtime());
return ($t[0] + $t[1]);
}
To get millisecond timestamp from PHP DateTime object:
<?php
date_default_timezone_set('UTC');
$d = new \DateTime('some_data_string');
$mts = $d->getTimestamp().substr($d->format('u'),0,3); // millisecond timestamp
PHP 7
This function has its return type declared.
function timestamp_ms(): int {
$times = gettimeofday();
$seconds = strval($times["sec"]);
$milliseconds = strval(floor($times["usec"]/1000));
$missingleadingzeros = 3-strlen($milliseconds);
if($missingleadingzeros >0){
for($i = 0; $i < $missingleadingzeros; $i++){
$milliseconds = '0'.$milliseconds;
}
}
return intval($seconds.$milliseconds);
}
PHP 5
function timestamp_ms() {
$times = gettimeofday();
$seconds = strval($times["sec"]);
$milliseconds = strval(floor($times["usec"]/1000));
$missingleadingzeros = 3-strlen($milliseconds);
if($missingleadingzeros >0){
for($i = 0; $i < $missingleadingzeros; $i++){
$milliseconds = '0'.$milliseconds;
}
}
return intval($seconds.$milliseconds);
}
when you need the millisecond in str format, I think you should use:
public function get_millisecond() {
list($milliPart, $secondPart) = explode(' ', microtime());
$milliPart = substr($milliPart, 2, 3);
return $secondPart . $milliPart;
}
this will fix the bug int some get millisecond example where the milli part is like : 0.056. some example convert the milli part to float, your will get 56 instead of 056. I think some one want 056.
especially when you need the millisecond to order some data.
hope will help. :)
I recently had this problem to get a timestamp in milliseconds. To just multiply the unix timestamp by 1000 did not resolve the problem because i had to compare two database entrys very precicely. Aparently the php datetime object can´t handle milliseconds/microseconds but its stored in the datetime string anyway. So here is my solution:
$dateObject = new \DateTime('2015-05-05 12:45:15.444', new \DateTimeZone('Europe/London'));
$millis = $dateObject->format('v');
echo $dateObject->getTimestamp()*1000+$millis;
This should also work with microseconds if you use format->('u') (and of course multiply the timestamp by 1000000) instead. I hope you find this useful.
Something like this:
$mili_sec_time = $_SERVER['REQUEST_TIME_FLOAT'] * 1000;
Gives float type representing miliseconds from UNIX epoch to starts of the request.
$timestamp = str_replace(".","",number_format((float)microtime(true),2,'.',''));
Related
This is a two part problem which should be trivial but date and time handling in PHP seems to be anything but and everything I've tried so far has either given incorrect results or crashed my program
I'm trying to replicate the following two SQL Server commands in PHP
Count the days since the start of the millennium
select (cast (DATEDIFF(day,'2000-01-01',getdate()) as int)
Count the number of seconds since midnight
datediff(second,convert(date,getdate()),getdate())
I've tried all combinations of date_diff, getdate, strotime and more but nothing seems to give me a properly ISO formatted datetime or a workable method of calculating days and seconds elapsed.
I'm using PHP7 so should have all built-in functions up to date.
What am I missing?
edit: sample input data.
today's date in format '2020-11-22 16:57:10.112'
a given date in format '2000-01-01 00:00:00.000'
expected output data : 7631 days
today's date in format '2020-11-22 16:57:10.112'
previous midnight in format '2020-11-22 00:00:00.000'
expected output data : 61215 seconds
It's rather easy to do if you know your way around DateTime:
function daysSinceStartOfMillennium(DateTimeImmutable $date): int
{
$millenniumStart = new DateTimeImmutable('2000-01-01');
return $date->diff($millenniumStart)->days;
}
function secondsSinceMidnightOfDate(DateTimeImmutable $date): int
{
$midnightToday = new DateTimeImmutable('today');
$diff = $date->diff($midnightToday);
return $diff->s // seconds
+ $diff->i * 60 // minutes to seconds
+ $diff->h * 60 * 60 // hours to seconds
;
}
You could also modify the functions to take date strings as arguments and create a DateTime object inside them.
I opted to create a descriptive variable inside the millennium function to better convey the solution. The creation of this variable can be omitted if you wish and the argument passed directly into the return statement:
return $date->diff(new DateTimeImmutable('2000-01-01'))->days;
Note that if you only need to use these function for the current date, they can be simplified to take no arguments:
function daysSinceStartOfMillennium(): int
{
$millenniumStart = new DateTimeImmutable('2000-01-01');
return (new DateTimeImmutable())->diff($millenniumStart)->days;
}
function secondsSinceMidnight(): int
{
$midnightToday = new DateTimeImmutable('today');
$diff = (new DateTimeImmutable())->diff($midnightToday);
return $diff->s // seconds
+ $diff->i * 60 // minutes to seconds
+ $diff->h * 60 * 60 // hours to seconds
;
}
I have here a mysql query that get the average of the column(the column data type is 'time'). The column values for example are:
00:00:55, 00:00:59, 00:01:03
SELECT AVG(TIME_TO_SEC(column_name)) FROM table_name)AS average_result
In my Php I formatted the result this way:
<?php foreach($display_average as $da){
echo date("H:i:s", ($da["average_result"]));
}
?>
Outputs: 08:00:59 instead of 00:00:59, Why does this starts with 08? Or did I miss something? Thanks!
Both PHP's date/time functions and MySQL's date/time data types handle wall clock timestamps, not durations; i.e. 00:00:55 means fifty-five seconds past midnight. This is not what you want; you couldn't handle durations longer than 23 hours, 59 minutes, 59 seconds, because the data types and functions you're using are handling clock time, which cannot exceed these values.
Your specific issue stems from timezone settings. Your larger issue is that you need to store simple integer values expressing elapsed seconds or minutes; not timestamps. To format that into a human readable string in PHP you can use the DateInterval class.
see php manul, about the date_default_timezone_set your timezone is +8
the default date.timezone of PHP is utc, u can change it to date.timezone = PRC
date_default_timezone_set('UTC');
echo date("H:i:s", 59);//00:00:59
//date_default_timezone_set('RPC');
//echo date("H:i:s", 59);//08:00:59
Always go for standard/formal approaches. But if anyhow you need it custom, then you can do almost everything with programming. Here we go
Get your time as numbers (number of seconds in your time filed) from database as
SELECT
AVG
(
HOUR(column_name) * 3600
+ MINUTE(column_name) * 60
+ SECOND(column_name)
) AS numeric_average_result FROM table_name
Now you can convert number of seconds to proper time as
foreach($display_average as $da)
{
$r = numToTime($da["numeric_average_result"]);
echo "<br>".$r;
}
function numToTime($num)
{
$seconds = $num%60;
$num = (int)($num/60);
$minutes = $num%60;
$hours = (int)($num/60);
return make2digit($hours).":".make2digit($minutes).":".make2digit($seconds);
}
function make2digit($val)
{
if(strlen($val) == 1)
return "0".$val;
else
return $val;
}
I need a timestamp code similar to this JavaScript code:
new Date().getTime()
I tried this PHP code:
$date = new DateTime();
$ts = $date->getTimestamp();
which returns 1376399143 but the JavaScript code returns 1376399143263, I think my PHP code generates a timestamp for only the date. How can I get the timestamp for the time portion as well?
use the code below
$time = mktime(date("H"),date("i"),date("s"),date("n"),date("j"),date("Y"));
echo $time;
for details information on mktime , check this link
You could use microtime, but if you do not need the additional precision (which will get lost because of networking), just divide the javascript time by 1000.
You should use microtime
$seconds = microtime(true); // false = int, true = float
echo round(($seconds * 1000));
The php code generates the timestamp for date and time, but it returns the number of seconds from 1-1-1970. Javascript returns the value in miliseconds.
You could use microtime(true)*1000; for a similar result that Javascript.
I'm being told that this below method of calculating the user's local time is sometimes not working. What's the best way to do this in PHP? What do you do?
public function getTimeOffset ($time) {
$this->_cacheTimeOffset();
if ($this->timeOffsetExecuted) {
$d = date("O");
$neg = 1;
if (substr($d, 0, 1) == "-") {
$neg = -1;
$d = substr($d, 1);
}
$h = substr($d, 0, 2)*3600;
$m = substr($d, 2)*60;
return $time + ($neg * ($h + $m) * -1) + (($this->timeOffset + $this->getDstInUse()) * 3600);
}
return $time;
}
Use the DateTime extension, such as DateTime::getOffset,
or DateTimeZone::getOffset
Some countries might have perform several timezone update,
this method DateTimeZone::getTransitions reveal the transition history
Just answered a very similar question over here. I recommend you check that one out; I explained the two preferred ways of doing timezone offset calculation (using simple math, and then the datetimezone and datetime classes) pretty thoroughly.
The first way would be the easiest
(and most logical) way, and that is to
store their offset (if you already
have it, that is) and multiply that by
3600 (1 hour in seconds), and then add
that value to the current unix timestamp to get their final time of
running.
Another way to do it is to use the
DateTime and DateTimeZone classes.
How these two classes work, as shown
here, is that you create two
DateTimeZone objects, one with your
timezone and one with theirs; create
two DateTime objects with the first
parameters being "now" and the
second being the reference to the
DateTimeZone objects above
(respectively); and then call the
getOffset method on your timezone
object passing their timezone object
as the first parameter, ultimately
getting you the offset in seconds that
can be added to the current unix
timestamp to get the time that their
job needs to run.
date('Z');
returns the UTC offset in seconds.
A quick solution:
<?php echo date('g:i a', strtotime("now + 10 hours 30 minutes")); ?>
How to get millisecond between two DateTime objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
I get the error
Call to undefined method DateTime::getTimestamp()
In the strict sense, you can't.
It's because the smallest unit of time for the DateTime class is a second.
If you need a measurement containing milliseconds then use microtime()
Edit:
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00 and 2038-01-19 03:14:07 (see Year 2038 problem).
Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:
function dateTimeToMilliseconds(\DateTime $dateTime)
{
$secs = $dateTime->getTimestamp(); // Gets the seconds
$millisecs = $secs*1000; // Converted to milliseconds
$millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
return $millisecs;
}
It requires however that your DateTime object contains the microseconds (u in the format):
$date_str = "20:46:00.588";
$date = DateTime::createFromFormat("H:i:s.u", $date_str);
This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.
With this function, your code would become the following :
$date_str = "1990-08-07 20:46:00.588";
$date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
$msNow = (int)microtime(true)*1000;
echo $msNow - dateTimeToMilliseconds($date1);
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the 'u' format string.
<?php
// Instantiate a DateTime with microseconds.
$d = new DateTime('2011-01-01T15:03:01.012345Z');
// Output the microseconds.
echo $d->format('u'); // 012345
// Output the date with microseconds.
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345
// Unix Format
echo "<br>d2: ". $d->format('U.u');
function get_data_unix_ms($data){
$d = new DateTime($data);
$new_data = $d->format('U.u');
return $new_data;
}
function get_date_diff_ms($date1, $date2)
{
$d1 = new DateTime($date1);
$new_d1 = $d1->format('U.u');
$d2 = new DateTime($date2);
$new_d2 = $d2->format('U.u');
$diff = abs($new_d1 - $new_d2);
return $diff;
}
https://www.php.net/manual/en/class.datetime.php
Here's a function to do that + tests.
https://gist.github.com/vudaltsov/0bb623b9e2817d6ce359eb88cfbf229d
DateTime dates are only stored as whole seconds. If you still need the number of milliseconds between two DateTime dates, then you can use getTimestamp() to get each time in seconds (then get the difference and turn it into milliseconds):
$seconds_diff = $date2.getTimestamp() - $date.getTimestamp()
$milliseconds_diff = $seconds_diff * 1000