custom field value date convert to unix timestamp problems

For some reason, I’m having difficulty converting a date value stored in a meta field to a unix timestamp (and back again). If I save the date as a string it all works fine, but if I convert it to a timestamp using strtotime it won’t save the value.

My working code looks like this:

Read More
<?php

add_action( 'add_meta_boxes', 'rs_add_date' );
function rs_add_date() {
    add_meta_box( 'rs_add_date', 'Date', 'rs_add_date_create_meta_box', 'concerts', 'normal', 'high' );
}
function rs_add_date_create_meta_box( $post ) {
    $date = get_post_meta($post->ID, 'rs_date', true);
    echo 'Choose a date for the event';
    wp_nonce_field( plugin_basename(__FILE__), 'rs_date_nonce');
?>
    <p>Date (dd/mm/yyyy) <input type="text" name="rs-date" id="rs-date" value="<?php echo $date; ?>"></p>
<?php
}


// Save the new meta

add_action('save_post', 'rs_date_save_meta');
function rs_date_save_meta( $post_id ) {

    if(!wp_verify_nonce( $_POST['rs_date_nonce'], plugin_basename(__FILE__) ) )
        return;
    if(!current_user_can('edit_posts') )
        return;
    $date = $_POST['rs-date'];
    update_post_meta($post_id, 'rs_date', $date);
}
?>

But if I change it to the following it won’t work:

<?php
add_action( 'add_meta_boxes', 'rs_add_date' );
function rs_add_date() {
    add_meta_box( 'rs_add_date', 'Date', 'rs_add_date_create_meta_box', 'concerts', 'normal', 'high' );
}
function rs_add_date_create_meta_box( $post ) {
    $date = get_post_meta($post->ID, 'rs_date', true);
    $date = time("d/m/Y", $date);
    echo 'Choose a date for the event';
    wp_nonce_field( plugin_basename(__FILE__), 'rs_date_nonce');
?>
    <p>Date (dd/mm/yyyy) <input type="text" name="rs-date" id="rs-date" value="<?php echo $date; ?>"></p>
<?php
}


// Save the new meta

add_action('save_post', 'rs_date_save_meta');
function rs_date_save_meta( $post_id ) {

    if(!wp_verify_nonce( $_POST['rs_date_nonce'], plugin_basename(__FILE__) ) )
        return;
    if(!current_user_can('edit_posts') )
        return;
    $date = $_POST['rs-date'];
    $date = strtotime($date);
    update_post_meta($post_id, 'rs_date', $date);
}
?>

Scratching my head here! Cheers

Related posts

Leave a Reply

1 comment

  1. Looking at http://www.php.net/manual/en/datetime.formats.date.php I dont think strtotime will convert a DD/MM/YYYY to time correctly.

    However it can do MM/DD/YYYY or YYYY/MM/DD.

    Try using the date format of YYYY/MM/DD

    Or if thats not to your liking then you can use the same date format but you will have to, on save, split up the date and convert it to unix datestamp a diff way. You could use:

    $date = "dd/mm/yyyy";
    $date = explode("/", $date);
    $date = mktime(0, 0, 0, (int)$date[1], (int)$date[0], (int)$date[2]);