php date time now | how to blend using gimp | how to remove css from my site | php auto tweet script
 


 

How to Get Current Datetime (NOW) with 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

<?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

<?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:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
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:

/* server timezone */
define('CONST_SERVER_TIMEZONE', 'UTC');

/* server dateformat */
define('CONST_SERVER_DATEFORMAT', 'YmdHis');

In this case, you may use the following simple function:

<?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!

Related Posts

You may also be interested in

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

More tips