Which PHP function can return the current date/time?
The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions are called to.
I'm in Melbourne, Australia so I have something like this:
date_default_timezone_set('Australia/Melbourne');
Or another example is LA - US:
date_default_timezone_set('America/Los_Angeles');
You can also see what timezone the server is currently in via:
date_default_timezone_get();
So something like:
$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;
So the short answer for your question would be:
// Change the line below to your timezone!
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());
Then all the times would be to the timezone you just set :)
// Simply:
$date = date('Y-m-d H:i:s');
// Or:
$date = date('Y/m/d H:i:s');
// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';
/**
* This time is based on the default server time zone.
* If you want the date in a different time zone,
* say if you come from Nairobi, Kenya like I do, you can set
* the time zone to Nairobi as shown below.
*/
date_default_timezone_set('Africa/Nairobi');
// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');
// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.
For a time-zone reference, see List of Supported Timezones.
Since PHP 5.2.0 you can use the DateTime() class:
use \Datetime;
$now = new DateTime();
echo $now->format('Y-m-d H:i:s'); // MySQL datetime format
echo $now->getTimestamp(); // Unix Timestamp -- Since PHP 5.3
And to specify the timezone:
$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London')); // Another way
echo $now->getTimezone();
Reference: Here's a link
This can be more reliable than simply adding or subtracting the number of seconds in a day or a month to a timestamp because of daylight saving time.
The PHP code
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
PHP's time() returns a current Unix timestamp. With this, you can use the date() function to format it to your needs.
$date = date('Format String', time());
As Paolo mentioned in the comments, the second argument is redundant. The following snippet is equivalent to the one above:
$date = date('Format String');
You can either use the $_SERVER['REQUEST_TIME'] variable (available since PHP 5.1.0) or the time() function to get the current Unix timestamp.
You can use both the $_SERVER['REQUEST_TIME'] variable or the time() function. Both of these return a Unix timestamp.
Most of the time these two solutions will yield the exact same Unix Timestamp. The difference between these is that $_SERVER['REQUEST_TIME'] returns the time stamp of the most recent server request and time() returns the current time. This may create minor differences in accuracy depending on your application, but for most cases both of these solutions should suffice.
Based on your example code above, you are going to want to format this information once you obtain the Unix Timestamp. Unformatted Unix time looks like: 1232659628
So in order to get something that will work, you can use the date() function to format it.
A good reference for ways to use the date() function is located in the PHP Manual.
As an example, the following code returns a date that looks like this: 01/22/2009 04:35:00 pm :
echo date("m/d/Y h:i:s a", time());
PHP's date function can do this job.
date()
Description:
string date(string $format [, int $timestamp = time()])
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
Examples:
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
For the new PHP programmer might confuse why there are lot of method for to get current date and time and which one to use in their project.
1. date method (PHP 4, PHP 5, PHP 7)
This is the very common and very easiest way to get the date and time in php.
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
You can learn more about it in here
2. DateTime class (PHP 5 >= 5.2.0, PHP 7)
when you want to use PHP with OOP, this is the best way to get date and time.
<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('#946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
You can learn more about it in here
3. Carbon Date time package
if you are using Composer, Laravel, Symfony or any kinda framework this is the best way to get the date and time. Also this package extends DateTime class in php so you use all the method in Datetime class.
This in-built in frameworks like laravel so you don't have to install it separately.
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');
$officialDate = Carbon::now()->toRfc2822String();
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');
if (Carbon::now()->isWeekend()) {
echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
You can learn more about it in here
Hope this helps and if you know any other way to get the date and time feel free to edit the answer.
Use:
$date = date('m/d/Y h:i:s a', time());
It works.
its very simple
echo $date = date('Y-m-d H:i:s');
$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('d-m-Y H:i:s');
Update
//Also get am/pm in datetime:
echo $date->format('d-m-Y H:i:s a'); // output 30-12-2013 10:16:15 am
For the date format, PHP date() Function is useful.
echo date("d-m-Y H:i:sa");
This code will get the date and time of the server that the code runs on.
You can use this format also:
$date = date("d-m-Y");
Or
$date = date("Y-m-d H:i:s");
According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the 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');
?>
<?php
echo "<b>".date('l\, F jS\, Y ')."</b>";
?>
Prints like this
Sunday, December 9th, 2012
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>
Set your time zone:
date_default_timezone_set('Asia/Calcutta');
Then call the date functions
$date = date('Y-m-d H:i:s');
date(format, timestamp)
The date function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
And the parameters are -
format - Required. Specifies the format of the timestamp
timestamp - (Optional) Specifies a timestamp. Default is the current date and time
How to get a simple 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:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Some useful links
gmdate() - Format a
GMT/UTC date/time
idate() - Format a
local time/date as integer
getdate() - Get
date/time information
getlastmod() -
Gets time of last page modification
mktime() - Get Unix
timestamp for a date
strftime() - Format
a local time/date according to locale settings
time() - Return current
Unix timestamp
strtotime() -
Parse about any English textual datetime description into a Unix
timestamp
Predefined DateTime
Constants
The date format depends too:
echo date("d/m/Y H:i:sa"); // 13/04/2017 19:38:15pm
Very simple
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y H:i:s', time());
If you want a different timescale, please use:
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
date_default_timezone_set("Asia/Calcutta");
echo date("Y/m/d H:i:s");
date_default_timezone_set('Europe/Warsaw');
echo("<p class='time'>".date('H:i:s')."</p>");
echo("<p class='date'>".date('d/m/Y')."</p>");
You can use this code:
<?php
$currentDateTime = date('Y-m-d H:i:s');
echo $currentDateTime;
?>
I found that the simplest way of getting the current time in PHP is something like this.
//Prints out something like 10:00am Just be sure to set your timezone correctly.
date_default_timezone_set("America/Chicago");
$TIME = date('G:ia');
Another simple way is to take the timestamp of the current date and time. Use mktime() function:
$now = mktime(); // Return timestamp of the current time
Then you can convert this to another date format:
//// Prints something like: Thursday 26th of January 2017 01:12:36 PM
echo date('l jS \of F Y h:i:s A',$now);
More date formats are here:
http://php.net/manual/en/function.date.php
The best way to get the current time and date is by the date function in PHP:
$date = date('FORMAT'); // FORMAT E.g.: Y-m-d H:i:s
$current_date = date('Y-m-d H:i:s');
With the Unix timestamp:
$now_date = date('FORMAT', time()); // FORMAT Eg : Y-m-d H:i:s
To set the server time zone:
date_default_timezone_set('Asia/Calcutta');
A different time zone list is here.
Your Country Time Zone: List of Supported Timezones
date_default_timezone_set('Asia/Kolkata');
$dateYmd = date('Y-m-d');
echo "Current Year Month Day: $dateYmd";
Current Year Month Day: 2022-01-03
$datehms = date('h:i:s');
echo "Current Hour Minute Second: $datehms";
Current Hour Minute Second: 11:05:38
If you are Bangladeshi, and if you want to get the time of Dhaka then use this:
$date = new DateTime();
$date->setTimeZone(new DateTimeZone("Asia/Dhaka"));
$get_datetime = $date->format('d.m.Y H:i:s');
Normally, this function for date is useful for everyone: date("Y/m/d");
But time is something different, because the time function depends on either the PHP version or system date.
So probably use it like this to get our own time zone:
$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('H:m:s');
This function shows the 24 hours time.
Related
I have a timestamp stored in a session (1299446702).
How can I convert that to a readable date/time in PHP? I have tried srttotime, etc. to no avail.
Use PHP's date() function.
Example:
echo date('m/d/Y', 1299446702);
strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.
If you have a timestamp that you want to use (apparently you do), it is the second argument of date().
I just added H:i:s to Rocket's answer to get the time along with the date.
echo date('m/d/Y H:i:s', 1299446702);
Output: 03/06/2011 16:25:02
$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';
$date = new \DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
$date->setTimestamp($timestamp);
echo $date->format($datetimeFormat);
result: 2016-06-07 14:29:00
Other time zones:
Africa
America
Antarctica
Arctic
Asia
Atlantic
Australia
Europe
Indian
Pacific
Others
If you are using PHP date(), you can use this code to get the date, time, second, etc.
$time = time(); // you have 1299446702 in time
$year = $time/31556926 % 12; // to get year
$week = $time / 604800 % 52; // to get weeks
$hour = $time / 3600 % 24; // to get hours
$minute = $time / 60 % 60; // to get minutes
$second = $time % 60; // to get seconds
If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:
$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);
Following #sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.
$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored
You may check PHP's manual for DateTime::createFromFormat for more info and options.
Try this one:
echo date('m/d/Y H:i:s', 1541843467);
$epoch = 1483228800;
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:
Format Output
r ----- Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c ----- 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y ----- Mar/15/2017
d-m-Y ----- 15-03-2017
Y-m-d H:i:s ----- 2017-03-15 12:00:00
Try it.
<?php
$timestamp=1333342365;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
You can try this:
$mytimestamp = 1465298940;
echo gmdate("m-d-Y", $mytimestamp);
Output :
06-07-2016
Unless you need a custom date and time format, it's easier, less error-prone, and more readable to use one of the built-in date time format constants:
echo date(DATE_RFC822, 1368496604);
echo date("l M j, Y",$res1['timep']);
This is really good for converting a unix timestamp to a readable date along with day. Example:
Thursday Jul 7, 2016
echo 'Le '.date('d/m/Y', 1234567890).' à '.date('H:i:s', 1234567890);
I have used this:
<?php echo date('d/m/Y H:i a', $row['start_time']); ?>
Please see this code:
// Instantiate DateTime object with users timezone
$date = new \DateTime(null, new \DateTimeZone(Yii::$app->formatter->timeZone));
// Get current year
echo $date->format('l, F j Y g:i:s A');
echo "<br>\n";
/* Get year the event took place */
// Change the timezone to the timezone we will be giving it a unix timestamp in
$date->setTimezone(new \DateTimeZone(Yii::$app->formatter->defaultTimeZone));
$utc_time = time() - date('Z');
$utc_time = strtotime('- 1 Year', $utc_time);
// Update our time
$date->setTimestamp($utc_time);
// Now change the timezone back to the users timezone
$date->setTimezone(new \DateTimeZone(Yii::$app->formatter->timeZone));
// Get year the thread was started in...
echo $date->format('l, F j Y g:i:s A');
Yii::$app->formatter->defaultTimeZone is set to UTC and the reason we are changing to that is because the timestamp we are passing to it will be coming from the database in UTC, which is stored in the database by doing something like:
time() - date('Z')
The above will output something like:
Saturday, August 29 2015 11:28:54 PM
Friday, August 29 2014 3:28:54 PM
As you can see the second time output is incorrect (the hours aren't right).
What I am trying to do is get the current hear (works) and then get the year from the unix timestamp which we will be retrieving from the database; but as stated above this year will be returned as UTC and hence needs to be converted back to the users timezone somehow.
What am I doing wrong here?
As proposed via comments, here you have a function I use to convert date/time between different timezones:
function convert_time($cur_time, $tz_name_ini, $tz_name_res)
{
$tz1 = new DateTimeZone($tz_name_ini);
$tz2 = new DateTimeZone($tz_name_res);
$dt1 = new DateTime("now", $tz1);
$dt2 = new DateTime("now", $tz2);
$offset1 = $tz1->getOffset($dt1);
$offset2 = $tz2->getOffset($dt2);
$diff_offset = $offset2 - $offset1;
return date("l, F j Y g:i:s A", $cur_time + $diff_offset);
}
For example, if my server is in Denver and I want the application to show the time in Madrid, I would call the function as follows:
$tz_name_ini = "America/Denver";
$tz_name_res = "Europe/Madrid";
convert_time(time(), $tz_name_ini, $tz_name_res);
List with all the supported timezones: http://php.net/manual/en/timezones.php
Using PHP, I want to convert UNIX timestamps to date strings similar to this: 2008-07-17T09:24:17Z
How do I convert a timestamp such as 1333699439 to 2008-07-17T09:24:17Z?
Try gmdate like this:
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
use date function date ( string $format [, int $timestamp = time() ] )
Use date('c',time()) as format to convert to ISO 8601 date (added in PHP 5) - 2012-04-06T12:45:47+05:30
use date("Y-m-d\TH:i:s\Z",1333699439) to get 2012-04-06T13:33:59Z
Here are some of the formats date function supports
<?php
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
?>
Assuming you are using PHP5.3 then the modern way of handling dates is via the native DateTime class. To get the current time you can just call
$currentTime = new DateTime();
To create a DateTime object from a specific timestamp (i.e. not now)
$currentTime = DateTime::createFromFormat( 'U', $timestamp );
To get a formatted string you can then call
$formattedString = $currentTime->format( 'c' );
See the manual page here
It is very important to set a default timezone to get the correct result
<?php
// set default timezone
date_default_timezone_set('Europe/Berlin');
// timestamp
$timestamp = 1307595105;
// output
echo date('d M Y H:i:s Z',$timestamp);
echo date('c',$timestamp);
?>
Online conversion help: http://freeonlinetools24.com/timestamp
<?php
$timestamp=1486830234542;
echo date('Y-m-d H:i:s', $timestamp/1000);
?>
The DateTime class takes a string in the constructor. If you prefix the timestamp with a #-character you create a DateTime object with the timestamp. For formating use the 'c' format ... a predefined ISO 8601 compound format.
If could use the DateTime class like this ... set the right timezone or leave it out if you want a UTC time.
$dt = new DateTime('#1333699439');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('c');
https://www.php.net/manual/en/book.datetime.php
https://www.php.net/manual/en/datetime.format.php
more examples and timezones https://time.einfach.jetzt/?t=1333699439
$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);
This should work to.
You can do like as.....
$originalDate = "1585876500";
echo $newDate = date("Y-m-d h:i:sa", date($originalDate));
most people doesn't read comment, and there is problem with gmdate() in accepted answer, it return time in GMT, so if we use date_default_timezone_set(zone) it will not work, instead use date().
<?php
$ts = 1664706166;
$date = date('Y-m-d H:i:s', $ts);
$gmdate = gmdate('Y-m-d H:i:s', $ts);
echo "date() : $date\n";
echo "gmdate(): $gmdate\n\n";
date_default_timezone_set("Asia/Jakarta");
$date = date('Y-m-d H:i:s', $ts);
$gmdate = gmdate('Y-m-d H:i:s', $ts);
echo "date() : $date\n";
echo "gmdate(): $gmdate <- GMT\n";
/* result
date() : 2022-10-02 10:22:46
gmdate(): 2022-10-02 10:22:46
After set timezone
date() : 2022-10-02 17:22:46
gmdate(): 2022-10-02 10:22:46 <- GMT
*/
I found the information in this conversation so helpful that I just wanted to add how I figured it out by using the timestamp from my MySQL database and a little PHP
<?= date("Y-m-d\TH:i:s\+01:00",strtotime($column['loggedin'])) ?>
The output was: 2017-03-03T08:22:36+01:00
Thanks very much Stewe you answer was a eureka for me.
I have a timestamp stored in a session (1299446702).
How can I convert that to a readable date/time in PHP? I have tried srttotime, etc. to no avail.
Use PHP's date() function.
Example:
echo date('m/d/Y', 1299446702);
strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.
If you have a timestamp that you want to use (apparently you do), it is the second argument of date().
I just added H:i:s to Rocket's answer to get the time along with the date.
echo date('m/d/Y H:i:s', 1299446702);
Output: 03/06/2011 16:25:02
$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';
$date = new \DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
$date->setTimestamp($timestamp);
echo $date->format($datetimeFormat);
result: 2016-06-07 14:29:00
Other time zones:
Africa
America
Antarctica
Arctic
Asia
Atlantic
Australia
Europe
Indian
Pacific
Others
If you are using PHP date(), you can use this code to get the date, time, second, etc.
$time = time(); // you have 1299446702 in time
$year = $time/31556926 % 12; // to get year
$week = $time / 604800 % 52; // to get weeks
$hour = $time / 3600 % 24; // to get hours
$minute = $time / 60 % 60; // to get minutes
$second = $time % 60; // to get seconds
If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:
$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);
Following #sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.
$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored
You may check PHP's manual for DateTime::createFromFormat for more info and options.
Try this one:
echo date('m/d/Y H:i:s', 1541843467);
$epoch = 1483228800;
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:
Format Output
r ----- Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c ----- 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y ----- Mar/15/2017
d-m-Y ----- 15-03-2017
Y-m-d H:i:s ----- 2017-03-15 12:00:00
Try it.
<?php
$timestamp=1333342365;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
You can try this:
$mytimestamp = 1465298940;
echo gmdate("m-d-Y", $mytimestamp);
Output :
06-07-2016
Unless you need a custom date and time format, it's easier, less error-prone, and more readable to use one of the built-in date time format constants:
echo date(DATE_RFC822, 1368496604);
echo date("l M j, Y",$res1['timep']);
This is really good for converting a unix timestamp to a readable date along with day. Example:
Thursday Jul 7, 2016
echo 'Le '.date('d/m/Y', 1234567890).' à '.date('H:i:s', 1234567890);
I have used this:
<?php echo date('d/m/Y H:i a', $row['start_time']); ?>
Which PHP function can return the current date/time?
The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions are called to.
I'm in Melbourne, Australia so I have something like this:
date_default_timezone_set('Australia/Melbourne');
Or another example is LA - US:
date_default_timezone_set('America/Los_Angeles');
You can also see what timezone the server is currently in via:
date_default_timezone_get();
So something like:
$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;
So the short answer for your question would be:
// Change the line below to your timezone!
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());
Then all the times would be to the timezone you just set :)
// Simply:
$date = date('Y-m-d H:i:s');
// Or:
$date = date('Y/m/d H:i:s');
// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';
/**
* This time is based on the default server time zone.
* If you want the date in a different time zone,
* say if you come from Nairobi, Kenya like I do, you can set
* the time zone to Nairobi as shown below.
*/
date_default_timezone_set('Africa/Nairobi');
// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');
// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.
For a time-zone reference, see List of Supported Timezones.
Since PHP 5.2.0 you can use the DateTime() class:
use \Datetime;
$now = new DateTime();
echo $now->format('Y-m-d H:i:s'); // MySQL datetime format
echo $now->getTimestamp(); // Unix Timestamp -- Since PHP 5.3
And to specify the timezone:
$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London')); // Another way
echo $now->getTimezone();
Reference: Here's a link
This can be more reliable than simply adding or subtracting the number of seconds in a day or a month to a timestamp because of daylight saving time.
The PHP code
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
PHP's time() returns a current Unix timestamp. With this, you can use the date() function to format it to your needs.
$date = date('Format String', time());
As Paolo mentioned in the comments, the second argument is redundant. The following snippet is equivalent to the one above:
$date = date('Format String');
You can either use the $_SERVER['REQUEST_TIME'] variable (available since PHP 5.1.0) or the time() function to get the current Unix timestamp.
You can use both the $_SERVER['REQUEST_TIME'] variable or the time() function. Both of these return a Unix timestamp.
Most of the time these two solutions will yield the exact same Unix Timestamp. The difference between these is that $_SERVER['REQUEST_TIME'] returns the time stamp of the most recent server request and time() returns the current time. This may create minor differences in accuracy depending on your application, but for most cases both of these solutions should suffice.
Based on your example code above, you are going to want to format this information once you obtain the Unix Timestamp. Unformatted Unix time looks like: 1232659628
So in order to get something that will work, you can use the date() function to format it.
A good reference for ways to use the date() function is located in the PHP Manual.
As an example, the following code returns a date that looks like this: 01/22/2009 04:35:00 pm :
echo date("m/d/Y h:i:s a", time());
PHP's date function can do this job.
date()
Description:
string date(string $format [, int $timestamp = time()])
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
Examples:
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
For the new PHP programmer might confuse why there are lot of method for to get current date and time and which one to use in their project.
1. date method (PHP 4, PHP 5, PHP 7)
This is the very common and very easiest way to get the date and time in php.
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
You can learn more about it in here
2. DateTime class (PHP 5 >= 5.2.0, PHP 7)
when you want to use PHP with OOP, this is the best way to get date and time.
<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('#946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
You can learn more about it in here
3. Carbon Date time package
if you are using Composer, Laravel, Symfony or any kinda framework this is the best way to get the date and time. Also this package extends DateTime class in php so you use all the method in Datetime class.
This in-built in frameworks like laravel so you don't have to install it separately.
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');
$officialDate = Carbon::now()->toRfc2822String();
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');
if (Carbon::now()->isWeekend()) {
echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
You can learn more about it in here
Hope this helps and if you know any other way to get the date and time feel free to edit the answer.
Use:
$date = date('m/d/Y h:i:s a', time());
It works.
its very simple
echo $date = date('Y-m-d H:i:s');
$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('d-m-Y H:i:s');
Update
//Also get am/pm in datetime:
echo $date->format('d-m-Y H:i:s a'); // output 30-12-2013 10:16:15 am
For the date format, PHP date() Function is useful.
echo date("d-m-Y H:i:sa");
This code will get the date and time of the server that the code runs on.
You can use this format also:
$date = date("d-m-Y");
Or
$date = date("Y-m-d H:i:s");
According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the 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');
?>
<?php
echo "<b>".date('l\, F jS\, Y ')."</b>";
?>
Prints like this
Sunday, December 9th, 2012
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>
Set your time zone:
date_default_timezone_set('Asia/Calcutta');
Then call the date functions
$date = date('Y-m-d H:i:s');
date(format, timestamp)
The date function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
And the parameters are -
format - Required. Specifies the format of the timestamp
timestamp - (Optional) Specifies a timestamp. Default is the current date and time
How to get a simple 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:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Some useful links
gmdate() - Format a
GMT/UTC date/time
idate() - Format a
local time/date as integer
getdate() - Get
date/time information
getlastmod() -
Gets time of last page modification
mktime() - Get Unix
timestamp for a date
strftime() - Format
a local time/date according to locale settings
time() - Return current
Unix timestamp
strtotime() -
Parse about any English textual datetime description into a Unix
timestamp
Predefined DateTime
Constants
The date format depends too:
echo date("d/m/Y H:i:sa"); // 13/04/2017 19:38:15pm
Very simple
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y H:i:s', time());
If you want a different timescale, please use:
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
date_default_timezone_set("Asia/Calcutta");
echo date("Y/m/d H:i:s");
date_default_timezone_set('Europe/Warsaw');
echo("<p class='time'>".date('H:i:s')."</p>");
echo("<p class='date'>".date('d/m/Y')."</p>");
You can use this code:
<?php
$currentDateTime = date('Y-m-d H:i:s');
echo $currentDateTime;
?>
I found that the simplest way of getting the current time in PHP is something like this.
//Prints out something like 10:00am Just be sure to set your timezone correctly.
date_default_timezone_set("America/Chicago");
$TIME = date('G:ia');
Another simple way is to take the timestamp of the current date and time. Use mktime() function:
$now = mktime(); // Return timestamp of the current time
Then you can convert this to another date format:
//// Prints something like: Thursday 26th of January 2017 01:12:36 PM
echo date('l jS \of F Y h:i:s A',$now);
More date formats are here:
http://php.net/manual/en/function.date.php
The best way to get the current time and date is by the date function in PHP:
$date = date('FORMAT'); // FORMAT E.g.: Y-m-d H:i:s
$current_date = date('Y-m-d H:i:s');
With the Unix timestamp:
$now_date = date('FORMAT', time()); // FORMAT Eg : Y-m-d H:i:s
To set the server time zone:
date_default_timezone_set('Asia/Calcutta');
A different time zone list is here.
Your Country Time Zone: List of Supported Timezones
date_default_timezone_set('Asia/Kolkata');
$dateYmd = date('Y-m-d');
echo "Current Year Month Day: $dateYmd";
Current Year Month Day: 2022-01-03
$datehms = date('h:i:s');
echo "Current Hour Minute Second: $datehms";
Current Hour Minute Second: 11:05:38
If you are Bangladeshi, and if you want to get the time of Dhaka then use this:
$date = new DateTime();
$date->setTimeZone(new DateTimeZone("Asia/Dhaka"));
$get_datetime = $date->format('d.m.Y H:i:s');
Normally, this function for date is useful for everyone: date("Y/m/d");
But time is something different, because the time function depends on either the PHP version or system date.
So probably use it like this to get our own time zone:
$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('H:m:s');
This function shows the 24 hours time.