Get Wordpress current date/time
-
22-04-2021 - |
Question
In my plugin, I am trying to get the current date/time of the blog into the code but it seems to be returning a odd date/time. If i put a new post on the blog it does show the correct date/time so I am not sure what the issue is. Am I handling the code incorrectly? (Post Time: Published on: Feb 13, 2012 @ 22:45)
PHP Code
<?
$t_time = get_the_time( __( 'Y/m/d g:i:s A' ) );
echo "<h1>BLOG TIME</h1>";
echo $t_time . "<br>";
echo "<br>";
echo "<h1>SERVER TIME</h1>";
echo date("Y/m/d g:i:s A");
?>
OUTPUT BLOG TIME 2011/05/20 10:28:16 PM
SERVER TIME 2012/02/14 5:41:35 AM
Solution
There is a function in WordPress called current_time();
which you pass either 'timestamp' or 'mysql' to and it returns a time.
For more information: http://codex.wordpress.org/Function_Reference/current_time
OTHER TIPS
Since WordPress 5.3 current_time( 'timestamp' )
is No longer recommended. If you need to get a time that is adjusted for the site's timezone setting, the following functions are recommended to use:
1. current_datetime()
2. time()
3. get_post_datetime()
4. get_post_timestamp()
Why this change?
Date/Time component relied on WordPress timestamp (before WordPress 5.3), this was causing many bugs and lack of ability to go with upstream PHP.
Detail information here: https://make.wordpress.org/core/2019/09/23/date-time-improvements-wp-5-3/