How to get year, month and hour in WordPress?

PHP Date Format in WordPress function:

You’ll have to use the proper date format string (as used in PHP date function) in the WordPress get_the_date() function’s first parameter.

For example, to get the Date & Time in the format like 2018-07-23 23:59 (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like:

get_the_date('Y-m-d H:i');

Or, to get the Date & Time in the format like 23-07-2018 11:59 PM (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like:

get_the_date('d-m-Y h:i A');

So your full example CODE will be:

print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'd-m-Y h:i A' ) )  .  '</time>';

Mistakes in your CODE:

The idea in your CODE is not entirely wrong, only the CODE has two mistakes:

  1. You’ve used the the_date function, instead of get_the_date function. The way you’ve concatenated the string, the_date will not work as it prints the date immediately, doesn’t return as the get_the_date function does.

  2. You’ve used 'F j, Y', 'G:i' as two parameters, where as, it should be just one parameter: 'F j, Y G:i'.

So if you correct these two mistakes, the proper CODE will be:

print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'F j, Y G:i' ) )  .  '</time>';

Further Reading:

There are many other possibilities and all are in the Date Format string as described in PHP date function documentation. There are some useful examples in WordPress Codex as well.

Leave a Comment