Support

Account

Home Forums General Issues Working with a numbers field to show difference between two dates

Solving

Working with a numbers field to show difference between two dates

  • Trying to show the number of years an employee been working for a company, the idea is to register the year the employee started working and show the difference between start year and the current year.
    Im using a numbers field with a value between 1900-9999
    The issue is when i try to insert the value from the ACF field it simply shows 0 years of experience on the frontend.

    <?php if ( get_field( ’employe-start’ ) ) { ?>
    
    <?php
    
    $start = get_field( ’employe-start’ )
    
    $date_1 = new DateTime( $start );
    // Todays date
    $date_2 = new DateTime( date( 'Y' ) );
    $difference = $date_2->diff( $date_1 );
    ?>
    
    <p><?php echo (string)$difference->y; ?> years of experience</p>
    
    <?php } ?>
    

    If i insert a year like this:

    <?php if ( get_field( ’employe-start’ ) ) { ?>
    
    <?php
    
    $date_1 = new DateTime( '1999' );
    // Todays date
    $date_2 = new DateTime( date( 'Y' ) );
    $difference = $date_2->diff( $date_1 );
    ?>
    
    <p><?php echo (string)$difference->y; ?> years of experience</p>
    
    <?php } ?>

    It works, but i haven’t figured out how to format the ACF output for the code to work properly.

  • The problem is that using just the year is not a valid date format that us understood by date functions in PHP. You need to provide a month and day. http://php.net/manual/en/datetime.formats.date.php

  • Strange, if i format the first variable like my second example:

    $date_1 = new DateTime( '1999' );

    It will show “20 years of experience” on the frontend, if i change the variable to ( ‘1975’ ) it will show “44 years of experience” on the frontend so that part seems to work?

    My question was initially, how to insert my ACF value from the numbers field in the variable, but you are saying that even if i did, it won’t work?

  • I don’t know why it’s working. DateTime() object construction http://php.net/manual/en/datetime.construct.php refers to the date formatting page I linked to. Honestly, this sometimes looses me on what can be used. But if it’s working with a year in your tests then is should work if you use a year in the custom field.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.