php how to get current time
PHP Date and Time
The PHP date() function is used to format a date and/or a time.
The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
Parameter | Description |
---|---|
format | Required. Specifies the format of the timestamp |
timestamp | Optional. Specifies a timestamp. Default is the current date and time |
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
Other characters, like»/», «.», or «-» can also be inserted between the characters to add additional formatting.
The example below formats today’s date in three different ways:
Example
Use the date() function to automatically update the copyright year on your website:
Example
Get a Time
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
Example
Note that the PHP date() function will return the current date/time of the server!
Get Your Time Zone
If the time you got back from the code is not correct, it’s probably because your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the timezone you want to use.
The example below sets the timezone to «America/New_York», then outputs the current time in the specified format:
Example
Create a Date With mktime()
The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above).
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Syntax
The example below creates a date and time with the date() function from a number of parameters in the mktime() function:
Example
Create a Date From a String With strtotime()
The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
The example below creates a date and time from the strtotime() function:
Example
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
However, strtotime() is not perfect, so remember to check the strings you put in there.
More Date Examples
The example below outputs the dates for the next six Saturdays:
Example
The example below outputs the number of days until 4th of July:
Example
Complete PHP Date Reference
For a complete reference of all date functions, go to our complete PHP Date Reference.
The reference contains a brief description, and examples of use, for each function!
Get the Current Date and Time in PHP
Use date() and time() Function to Get the Current Date and Time in PHP
We could use built-in functions date() and time() to get the current date and time in PHP. These functions display the current date and time irrespective of the time zone. The correct syntax to use these two functions is as follows.
The built-in function date() has two parameters. The details of its parameters are as follows
Parameters | Description | |
---|---|---|
$format | mandatory | Date format to be displayed. It has several variations. It should be a string. |
$timestamp | optional | Timestamp to get the date. If it is omitted, then the current date is returned. |
It returns the date that is set according to the specified format.
The time() function accepts no parameters. It returns the current PHP timestamp. The timestamp is the number of seconds calculated since the Unix Epoch.
The program below shows how to get the current date and time irrespective of the time zone.
The format «m-d-Y h:i:s a» specifies the returned date with month, day and 4-digit year value, and the time in hours, minutes, and seconds.
One thing to note here is that the time is not set according to some time zone. It is the time displayed using Unix timestamp. If you want to check the current PHP time based on your time zone, you need to set the time zone manually.
For example, if you want to check the current time in Amsterdam, you have to set the time zone for Amsterdam manually. For this purpose, the PHP function date_default_timezone_set() is used. The correct syntax to use this function is as follows
It accepts only one parameter.
Parameters | Description | |
---|---|---|
$timezone | mandatory | It is a string that identifies the region for which we wish to set the time zone. You can check the list of supported time zones here. |
The program below will display the time after setting the time zone.
Use DateTime Object to Get the Current Date and Time in PHP
We will first create a DateTime object and then call format() function to display the date and time.
The function format() accepts one parameter.
Parameters | Description | |
---|---|---|
$format | mandatory | Format of the date and time. It should be a string. |
The example program that displays the current date and time is as follows.
The output is the date and time with the specified format. The time displayed is the time calculated since the Unix Epoch.
If you want to check the time according to a specific time zone, you will have to set the time zone manually. For this purpose, the PHP built-in function of DateTime class setTimezone() is used. The correct syntax to use this function is as follows.
The function setTimezone() accepts only one parameter. It returns a DateTime object on success and False on failure.
Parameter | Description | |
---|---|---|
$timezone | mandatory | It is a DateTimezone object that specifies the time zone. You can check the list of supported time zones here. |
The example program that displays the time according to a specific time zone is as follows.
How to get current time in milliseconds in PHP?
15 Answers 15
The short answer is:
90%: substr(microtime(true) * 1000, 0, 13);
There is also gettimeofday that returns the microseconds part as an integer.
Short answer:
64 bits platforms only!
[ If you are running 64 bits PHP then the constant PHP_INT_SIZE equals to 8 ]
Long answer:
If you want an equilvalent function of time() in milliseconds first you have to consider that as time() returns the number of seconds elapsed since the «epoch time» (01/01/1970), the number of milliseconds since the «epoch time» is a big number and doesn’t fit into a 32 bits integer.
The size of an integer in PHP can be 32 or 64 bits depending on platform.
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that’s 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.
If you have 64 bits integers then you may use the following function:
microtime() returns the number of seconds since the «epoch time» with precision up to microseconds with two numbers separated by space, like.
The second number is the seconds (integer) while the first one is the decimal part.
The above function milliseconds() takes the integer part multiplied by 1000
then adds the decimal part multiplied by 1000 and rounded to 0 decimals
Finally, that function is slightly more precise than
that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result. This is due to the limited precision of the float type ( microtime(true) returns a float). Anyway if you still prefer the shorter round(microtime(true)*1000); I would suggest casting to int the result.
Even if it’s beyond the scope of the question it’s worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microseconds without incurring in overflow.
That’s the same value you get with
In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.
Date/Time Functions
Table of Contents
User Contributed Notes 25 notes
I ran into an issue using a function that loops through an array of dates where the keys to the array are the Unix timestamp for midnight for each date. The loop starts at the first timestamp, then incremented by adding 86400 seconds (ie. 60 x 60 x 24). However, Daylight Saving Time threw off the accuracy of this loop, since certain days have a duration other than 86400 seconds. I worked around it by adding a couple of lines to force the timestamp to midnight at each interval.
When debugging code that stores date/time values in a database, you may find yourself wanting to know the date/time that corresponds to a given unix timestamp, or the timestamp for a given date & time.
The following script will do the conversion either way. If you give it a numeric timestamp, it will display the corresponding date and time. If you give it a date and time (in almost any standard format), it will display the timestamp.
All conversions are done for your locale/time zone.
For those who are using pre MYSQL 4.1.1, you can use:
TO_DAYS([Date Value 1])-TO_DAYS([Date Value 2])
For the same result as:
DATEDIFF([Date Value 1],[Date Value 2])
This dateDiff() function can take in just about any timestamp, including UNIX timestamps and anything that is accepted by strtotime(). It returns an array with the ability to split the result a couple different ways. I built this function to suffice any datediff needs I had. Hope it helps others too.
I needed a function that determined the last Sunday of the month. Since it’s made for the website’s «next meeting» announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form «January 26, 2003». I could probably have streamlined this quite a bit, but at least it’s transparent code. =)
/* The two functions calculate when the next meeting will
be, based on the assumption that the meeting will be on
the last Sunday of the month. */
I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :
Not really elegant, but tells you, if your installed timezonedb is the most recent:
Someone may find this info of some use:
Rules for calculating a leap year:
1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn’t (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).
In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.
The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.
I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.
Here are two functions that do exactly that:
Hope somebody finds this useful.
Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.
$sql= «SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
FROM your_table
WHERE field1 = ‘$value'»;
The query will return a temp table with coulms «field1» «Field2» «your_date»
The «your_date» will be formatted in a UNIX TIMESTAMP! Now you can use the PHP date() function to spew out nice date formats.
Hope this helps someone out there!
//function like dateDiff Microsoft
//not error in year Bissesto
PHP: How to get current time in hour:minute:second?
3 Answers 3
Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language’s capabilities.
Looking up a function is easy, just visit http://php.net/ and it will forward you to the appropriate place. For the date function, we’ll visit http://php.net/date.
We immediately learn a couple things about this function by examining its signature:
First, it returns a string. That’s what the first string in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).
In this code, d represents the day of the month (with a leading 0 is necessary). m represents the month, again with a leading zero if necessary. And Y represents the full 4-digit year. All of these are documented in the aforementioned link.
To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:
With this in mind, we can no create a new format string:
Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.