Sauter la navigation

[Résolu] Split: Calculate age from date field – show year, months, days

This support ticket is created Il y a 6 années et 1 mois. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

Ce sujet contient 4 réponses, a 2 voix.

Dernière mise à jour par francescoG-3 Il y a 6 années et 1 mois.

Assisté par: Minesh.

Auteur
Publications
#1156157

Sorry, you want to display exact age with Year, months, days?
Yes I want to do that!

#1156161

Minesh
Supporter

Les langues: Anglais (English )

Fuseau horaire: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

Well - To calculate the date difference in Years, Month and Days from current time, you can use the following shortcode:

add_shortcode( 'iam-eta', 'wpv_post_age_shortcode');
function wpv_post_age_shortcode( $atts ) {
   global $post;
 // gettitng time stamp
$bday = get_post_meta( $post->ID, 'wpcf-data-di-nascita', true );
$bday = new DateTime("@$ts");
$now = new DateTime('00:00:00');       // current date-time

// object with the difference between $now and $bday (y = year, m = month, d = day)
$diff = $now->diff($bday);

// output
return sprintf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
}
#1156179

This code send the post page in crash, I display only the menu bars and all content desappear...

And sorry, I have don't understand correctly your first question. So, I want to display only the correct age, not month and day remaining.

So, I think that the correct solution is the code in the previous ticket, but adding a condition.
The condition could be: if the months and days of the birthday are < than the today date then display $age-1 else display $age.

But I don't now to write that.

#1156191

Minesh
Supporter

Les langues: Anglais (English )

Fuseau horaire: Asia/Kolkata (GMT+05:30)

Ok - so you should use the following shortcode where you need to use the floor function to round down result value to nearest smallest integer:

add_shortcode( 'iam-eta', 'wpv_post_age_shortcode');
function wpv_post_age_shortcode( $atts ) {
   global $post;
 $timestamp = get_post_meta( $post->ID, 'wpcf-data-di-nascita', true );
$age = floor((time() - $timestamp) / ( 60*60*24* 365 )) ;
return $age;
}

You need to use floor function:
=> lien caché

#1156206

My issue is resolved now. Thank you!