How to Display Date in PHP


To get current datetime (now) with PHP you can use date with any PHP version, or better datetime class with PHP >= 5.2
Various date format expressions are available here.

Example using date

This expression will return NOW in format Y-m-d H:i:s
1
2
3
<?php
echo date('Y-m-d H:i:s');
?>

Example using datetime class

This expression will return NOW in format Y-m-d H:i:s
1
2
3
4
<?php
$dt = new DateTime();
echo $dt->format('Y-m-d H:i:s');
?>

A more complete approach

Above examples will return NOW using your server timezone, as it is defined in php.ini, for example:
1
2
3
4
[Date]
; Defines the default timezone used by the date functions
date.timezone = Europe/Athens
But, the best approach is to save dates to UTC. UTC (also called Zulu time) is the standard international time. All time zones are expressed as offsets of UTC. Especially, if your application users are located in different timezones. Using php DateTime class it is easy to compute the time in user timezone from UTC, and you don't have to worry about for Daylight Savings Time changes.
Define server timezone and server date format according to your preferences. My preferences are:
1
2
3
4
5
/* server timezone */
define('CONST_SERVER_TIMEZONE', 'UTC');
 
/* server dateformat */
define('CONST_SERVER_DATEFORMAT', 'YmdHis');
In this case, you may use the following simple function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
/**
 * Converts current time for given timezone (considering DST)
 *  to 14-digit UTC timestamp (YYYYMMDDHHMMSS)
 *
 * DateTime requires PHP >= 5.2
 *
 * @param $str_user_timezone
 * @param string $str_server_timezone
 * @param string $str_server_dateformat
 * @return string
 */
function now($str_user_timezone,
       $str_server_timezone = CONST_SERVER_TIMEZONE,
       $str_server_dateformat = CONST_SERVER_DATEFORMAT) {
 
  // set timezone to user timezone
  date_default_timezone_set($str_user_timezone);
 
  $date = new DateTime('now');
  $date->setTimezone(new DateTimeZone($str_server_timezone));
  $str_server_now = $date->format($str_server_dateformat);
 
  // return timezone to server default
  date_default_timezone_set($str_server_timezone);
 
  return $str_server_now;
}
?>
Hope to find it helpful. Your comments are welcomed!

Comments

Popular posts from this blog

Encryption And Decryption Functions In Vb.Net

How to Install Squirrel Mail in ubuntu