- PHP Date and Time
- The PHP Date() Function
- Syntax
- Get a Date
- Example
- PHP Tip — Automatic Copyright Year
- Example
- Get a Time
- Example
- Get Your Time Zone
- Example
- Create a Date With mktime()
- Syntax
- Example
- Create a Date From a String With strtotime()
- Syntax
- Example
- Example
- More Date Examples
- Example
- Example
- Complete PHP Date Reference
- filemtime
- Список параметров
- Возвращаемые значения
- Ошибки
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 30 notes
- filectime
- Errors/Exceptions
- Examples
- Notes
- See Also
- User Contributed Notes 9 notes
- PHP filemtime() Function
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
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:
- d — Represents the day of the month (01 to 31)
- m — Represents a month (01 to 12)
- Y — Represents a year (in four digits)
- l (lowercase ‘L’) — Represents the day of the week
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
echo «Today is » . date(«Y/m/d») . «
«;
echo «Today is » . date(«Y.m.d») . «
«;
echo «Today is » . date(«Y-m-d») . «
«;
echo «Today is » . date(«l»);
?>?php
PHP Tip — Automatic Copyright Year
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:
- H — 24-hour format of an hour (00 to 23)
- h — 12-hour format of an hour with leading zeros (01 to 12)
- i — Minutes with leading zeros (00 to 59)
- s — Seconds with leading zeros (00 to 59)
- a — Lowercase Ante meridiem and Post meridiem (am or pm)
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
$d=strtotime(«next Saturday»);
echo date(«Y-m-d h:i:sa», $d) . «
«;
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
$startdate = strtotime(«Saturday»);
$enddate = strtotime(«+6 weeks», $startdate);
?php
while ($startdate < $enddate) echo date("M d", $startdate) . "
«;
$startdate = strtotime(«+1 week», $startdate);
>
?>
The example below outputs the number of days until 4th of July:
Example
$d1=strtotime(«July 04»);
$d2=ceil(($d1-time())/60/60/24);
echo «There are » . $d2 .» days until 4th of July.»;
?>?php
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!
filemtime
Данная функция возвращает время последней записи блоков файла, иначе говоря, изменения содержания файла.
Список параметров
Возвращаемые значения
Возвращает время последнего изменения указанного файла или false в случае возникновения ошибки. Время возвращается в формате временной метки Unix, который подходит для передачи в качестве аргумента функции date() .
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примеры
Пример #1 Пример использования функции filemtime()
// Пример вывода: В последний раз файл somefile.txt был изменён: December 29 2002 22:16:23.
?php
$filename = ‘somefile.txt’ ;
if ( file_exists ( $filename )) echo «В последний раз файл $filename был изменён: » . date ( «F d Y H:i:s.» , filemtime ( $filename ));
>
?>
Примечания
Замечание:
Учтите, что обработка времени может отличаться в различных файловых системах.
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Смотрите также
- filectime() — Возвращает время изменения индексного дескриптора файла
- stat() — Возвращает информацию о файле
- touch() — Устанавливает время доступа и модификации файла
- getlastmod() — Получает время последней модификации страницы
User Contributed Notes 30 notes
This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this:
By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it’ll reload the stylesheet every time the modification date changes.
To get the last modification time of a directory, you can use this:
$getLastModDir = filemtime("/path/to/directory/.");
Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.
This comes in handy when you want just one ‘last updated’ message on the frontpage of your website and still taking all files of your website into account.
«this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it’s sub directories).»
This is not (necessarily) correct either. In *nix the timestamp can be independently set. For example the command «touch directory» updates the timestamp of a directory without file creation.
Also file removal will update the timestamp of a directory.
To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).
But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).
However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.
// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified ( $uri )
// default
$unixtime = 0 ;
$fp = fopen ( $uri , «r» );
if( ! $fp )
$MetaData = stream_get_meta_data ( $fp );
foreach( $MetaData [ ‘wrapper_data’ ] as $response )
// case: redirection
if( substr ( strtolower ( $response ), 0 , 10 ) == ‘location: ‘ )
$newUri = substr ( $response , 10 );
fclose ( $fp );
return GetRemoteLastModified ( $newUri );
>
// case: last-modified
elseif( substr ( strtolower ( $response ), 0 , 15 ) == ‘last-modified: ‘ )
$unixtime = strtotime ( substr ( $response , 15 ) );
break;
>
>
fclose ( $fp );
return $unixtime ;
>
?>
There’s a deeply-seated problem with filemtime() under Windows due to the fact that it calls Windows’ stat() function, which implements DST (according to this bug: http://bugs.php.net/bug.php?id=40568). The detection of DST on the time of the file is confused by whether the CURRENT time of the current system is currently under DST.
This is a fix for the mother of all annoying bugs:
function GetCorrectMTime ( $filePath )
$time = filemtime ( $filePath );
$isDST = ( date ( ‘I’ , $time ) == 1 );
$systemDST = ( date ( ‘I’ ) == 1 );
return ( $time + $adjustment );
>
?>
Dustin Oprea
filectime
Returns the time the file was last changed, or false on failure. The time is returned as a Unix timestamp.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Examples
Example #1 A filectime() example
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23.
$filename = ‘somefile.txt’ ;
if ( file_exists ( $filename )) echo » $filename was last changed: » . date ( «F d Y H:i:s.» , filectime ( $filename ));
>
Notes
Note:
Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create «Last Modified» footers on web pages) and fileatime() .
Note:
Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
See Also
User Contributed Notes 9 notes
This method gets all the files in a directory, and echoes them in the order of the date they were added (by ftp or whatever).
function dirList ( $directory , $sortOrder )
//Get each file and add its details to two arrays
$results = array();
$handler = opendir ( $directory );
while ( $file = readdir ( $handler )) <
if ( $file != ‘.’ && $file != ‘..’ && $file != «robots.txt» && $file != «.htaccess» ) $currentModified = filectime ( $directory . «/» . $file );
$file_names [] = $file ;
$file_dates [] = $currentModified ;
>
>
closedir ( $handler );
//Sort the date array by preferred order
if ( $sortOrder == «newestFirst» ) arsort ( $file_dates );
>else asort ( $file_dates );
>
//Match file_names array to file_dates array
$file_names_Array = array_keys ( $file_dates );
foreach ( $file_names_Array as $idx => $name ) $name = $file_names [ $name ];
$file_dates = array_merge ( $file_dates );
//Loop through dates array and then echo the list
foreach ( $file_dates as $file_dates ) $date = $file_dates ;
$j = $file_names_Array [ $i ];
$file = $file_names [ $j ];
$i ++;
echo «File name: $file — Date Added: $date .
«»;
>
I hope this is useful to somebody.
PHP filemtime() Function
The filemtime() function returns the last time the file content was modified.
Note: The result of this function is cached. Use clearstatcache() to clear the cache.
Syntax
Parameter Values
Technical Details
Return Value: | The last time the file content was modified as a Unix timestamp, FALSE on failure |
---|---|
PHP Version: | 4.0+ |
❮ PHP Filesystem Reference
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.