php datetime with milliseconds

Getting date format m-d-Y H:i:s.u from milliseconds

I am trying to get a formatted date, including the microseconds from a UNIX timestamp specified in milliseconds.

The only problem is I keep getting 000000, e.g.

php datetime with milliseconds. Смотреть фото php datetime with milliseconds. Смотреть картинку php datetime with milliseconds. Картинка про php datetime with milliseconds. Фото php datetime with milliseconds

16 Answers 16

This produces the following output:

From the PHP manual page for date formats:

Thanks goes to giggsey for pointing out a flaw in my original answer, adding number_format() to the line should fix the case of the exact second. Too bad it doesn’t feel quite as elegant any more.

A note on time zones in response to DaVe.

Normally the createFromFormat() method will use the local time zone if one is not specified.

However, the technique described here is initialising the DateTime object using microtime() which returns the number of seconds elapsed since the Unix Epoch (01 Jan 1970 00:00:00 GMT).

This means that the DateTime object is implicitly initialised to UTC, which is fine for server internal tasks that just want to track elapsed time.

If you need to display the time for a particular time zone then you need to set it accordingly. However, this should be done as a separate step after the initialisation (not using the third parameter of createFromFormat() ) because of the reasons discussed above.

The setTimeZone() method can be used to accomplish this requirement.

Produces the following output:

Note that if you want to input into mysql, the time format needs to be:

Источник

php: convert milliseconds to date

I Have a string that is equal to a date, represented as the number of milliseconds since the Unix epoch.

I am trying to output it into d-m-Y.

The string I was given was «1227643821310», and I am told that the result should be equal to 2-12-2008, but I keep getting a result of 25-11-2008

My code is as follows:

Any ideas as to why this might be?

6 Answers 6

You are already doing it right, 1227643821 is simply not 02-12-2008, it is indeed 25-11-2008.

I just added H:i:s like in the below example:

php datetime with milliseconds. Смотреть фото php datetime with milliseconds. Смотреть картинку php datetime with milliseconds. Картинка про php datetime with milliseconds. Фото php datetime with milliseconds

php datetime with milliseconds. Смотреть фото php datetime with milliseconds. Смотреть картинку php datetime with milliseconds. Картинка про php datetime with milliseconds. Фото php datetime with milliseconds

php datetime with milliseconds. Смотреть фото php datetime with milliseconds. Смотреть картинку php datetime with milliseconds. Картинка про php datetime with milliseconds. Фото php datetime with milliseconds

The only thing I can think of is try rounding off the decimal portion before converting it to a date. If that doesn’t change the result, then the result is correct.

Jeff, the important thing to understand when dealing with timestamps: they represent time which have passed from 0:00:00 01.01.1970 in GMT, not in your timezone (unless you are youself in GMT, of course).

1227643821 indeed represents the GMT time of 20:10:21 25.11.2008.

This is November 25th, 2008 in most of the world, however in timezones to the east of Moscow (and in the Moscow timezone itself in summer because of daylight savings time) it’s already November 26th. Since the most “extreme” east time zone is GMT+14, there’s no place in the world where the timestamp of 1227643821 can represent a date later then the 26th.

Author of the original value may have somehow mistaken when dealing with timezones. Or just plain mistaken. For example, when calculating the value, added seconds instead of milliseconds at some step.

Источник

Класс DateTime

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Введение

Обзор классов

Список изменений

Содержание

User Contributed Notes 26 notes

Set Timezone and formatting.

= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );

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.

// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );

There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.

/**
On my local machine this results in:

Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/

?>

Our solution was to create the following constant on our DateHelper object.

class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>

Small but powerful extension to DateTime

class Blar_DateTime extends DateTime <

= new Blar_DateTime ( ‘1879-03-14’ );

Albert Einstein would now be 130 years old.

Albert Einstein would now be 130 Years, 10 Months, 10 Days old.

Albert Einstein was on 2010-10-10 131 years old.

Example displaying each time format:

$dateTime = new DateTime();

The above example will output:

At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.

This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:

if you’d like to print all the built-in formats,

This might be unexpected behavior:

#or use the interval
#$date1->add(new DateInterval(«P1M»));

#will produce 2017-10-1
#not 2017-09-30

A good way I did to work with millisecond is transforming the time in milliseconds.

function timeToMilliseconds($time) <
$dateTime = new DateTime($time);

If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:

$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));

will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)

To get this done, you will need to set the timezone separately:

$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);

This will create a DateTime object set to «2010-07-05 08:00:00+0200»

It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.

For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:

please note that using

setTimezone
setTimestamp
setDate
setTime
etc..

$original = new DateTime(«now»);

so a datetime object is mutable

(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)

Create function to convert GregorianDate to JulianDayCount

Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.

Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.

It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:

Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:

$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)

Be aware of this behaviour:

In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.

Here is easiest way to find the days difference between two dates:

If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:

If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <

$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 01|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 04|[12]4|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 03|11|21)» ;
$regexpArray [ ‘i’ ] = «(?P16)» ;
$regexpArray [ ‘s’ ] = «(?P47)» ;

Источник

microtime

(PHP 4, PHP 5, PHP 7, PHP 8)

microtime — Возвращает текущую метку времени Unix с микросекундами

Описание

Функция microtime() возвращает текущую метку времени Unix с микросекундами. Эта функция доступна только на операционных системах, в которых есть системный вызов gettimeofday().

Список параметров

Возвращаемые значения

Примеры

Пример #1 Замер времени выполнения скрипта

// Спим некоторое время
usleep ( 100 );

Пример #2 Пример использования microtime() и REQUEST_TIME_FLOAT

Смотрите также

User Contributed Notes 20 notes

All these timing scripts rely on microtime which relies on gettimebyday(2)

This can be inaccurate on servers that run ntp to syncronise the servers
time.

For timing, you should really use clock_gettime(2) with the
CLOCK_MONOTONIC flag set.

This returns REAL WORLD time, not affected by intentional clock drift.

This may seem a bit picky, but I recently saw a server that’s clock was an
hour out, and they’d set it to ‘drift’ to the correct time (clock is speeded
up until it reaches the correct time)

Those sorts of things can make a real impact.

Any solutions, seeing as php doesn’t have a hook into clock_gettime?

Here is a solution to easily calculate the execution time of a script without having to alter any configuration parameter. It uses the former way of getting microseconds.

It is important to note that microtime(TRUE) does NOT always return a float (at least in PHP 5.x; I have not tested 7.x). If it happens to land on an exact second, it returns an integer instead.

The description of «msec», in this documentation, is very bad.

It is NOT the microseconds that have elapsed since «sec» (if so, it should be given as an integer, without the «0.» in the beginning of the string).
It IS the fractional part of the time elapsed since «sec», with microseconds (10E-6) precision, if the last «00» are not considered significant».
If the last two digits are significant, then we would have a precision of 10E-8 seconds.

mixed mini_bench_to(array timelist[, return_array=false])
return a mini bench result

-the timelist first key must be ‘start’
-default return a resume string, or array if return_array= true :
‘total_time’ (ms) in first row
details (purcent) in next row

The function to include :

Using microtime() to set ‘nonce’ value:

Out of the box, microtime(true) will echo something like:

Which is obviously less than microsecond accuracy. You’ll probably want to bump the ‘precision’ setting up to 16 which will echo something like:

*Internally* it will be accurate to the six digits even with the default ‘precision’, but a lot of things (ie. NoSQL databases) are moving to all-text representations these days so it becomes a bit more important.

* 14 at the time of writing

//timestamp in milliseconds:
intval ( microtime ( true )* 1000 )

//timestamp in microseconds:
intval ( microtime ( true )* 1000 * 1000 )

//timestamp in nanoseconds:
intval ( microtime ( true )* 1000 * 1000 * 1000 )

While doing some experiments on using microtime()’s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows.

The solution was to instead use gettimeofday()’s output, as its usec value followed no quantifiable pattern on any of the three test platforms.

A convenient way to write the current time / microtime as formatted string in your timezone as expression?

DateTime now is: 2018-06-01 14:54:58 Europe/Berlin
Microtime now is: 180601 14:54:58.781716 Europe/Berlin

I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8

$time_start = micro_time ();
sleep ( 1 );
$time_stop = micro_time ();

I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.

?>

However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm)
If system time change, result of this function can be unpredictable (much greater or less than zero).

Of the methods I’ve seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime.

I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn’t a problem of other things putting a load spike on the server. I’ll admit I didn’t take into account martijn at vanderlee dot com’s comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary.

Get date time with milliseconds

Test accuracy by running it in a loop.

//Function to convert microtime return to human readable units
//функция для конвертации времени, принимает значения в секундах

Источник

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

For example: I have set end date and time

then I have current date or start date with converted from microtime

I want my output to be like this: 00:00:02.452

2 Answers 2

You need to use microtime for the start/end values, and only format it for display at the end.

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:

I think this should work for you. You just have to figure your output format

php datetime with milliseconds. Смотреть фото php datetime with milliseconds. Смотреть картинку php datetime with milliseconds. Картинка про php datetime with milliseconds. Фото php datetime with milliseconds

Not the answer you’re looking for? Browse other questions tagged php microtime or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *