DateTime format not working as expected

HOW I NEED IT BUT DOESN’T WORK:

First template/page:

    $publishDeadline = new DateTime($publishDate);
    $publishDeadline->add($published_to_draft_delay);
    update_post_meta(get_the_ID(), 'publishDeadline', $publishDeadline);

Other template/page:

Read More
    $publishDeadline = get_post_meta( $post->ID, 'publishDeadline', true );  
    $publishDeadline->format('Y-m-d H:i:s');
    echo $publishDeadline;
  • Messes up page layout and it doesn’t echo anything
  • If I use var_dump($publishDeadline) instead of format in second code, I’ll get string(19) “2015-08-25 00:45:44”
  • How it’s saved in database (in phpMyAdmin): O:8:”DateTime”:3:{s:4:”date”;s:26:”2015-08-25 01:32:18.000000″;s:13:”timezone_type”;i:3;s:8:”timezone”;s:14:”Europe/Helsinki”;}
  • How I need it to be: It must be as DateTime in post_meta for being usable by my functions and I need formated output in front-end

HOW IT WORKS BUT THAT’S NOT WHAT I NEED:

First template/page:

    $publishDeadline = new DateTime($publishDate);
    $publishDeadline->add($published_to_draft_delay);
    $publishDeadline->format('Y-m-d H:i:s');
    update_post_meta(get_the_ID(), 'publishDeadline', $publishDeadline);

Other template/page:

    echo get_post_meta( $post->ID, 'publishDeadline', true );
  • Note how format is before updating post_meta & it works for mysterious reasons this way

Ask if there’s something you need to know.

Related posts

2 comments

  1. format doesn’t change the object, it just returns the date in the given format.

    Try this:

    update_post_meta(get_the_ID(), 'publishDeadline', $publishDeadline->format('Y-m-d H:i:s'));

  2. $publishDeadline->format(‘Y-m-d H:i:s’); works just fine after get_post_meta( $post->ID, ‘publishDeadline’, true );

    Problem was that 1 post’s post_meta was in other format from experimenting and debugging and it caused messed up layout and other errors.

Comments are closed.