Calculate Days Between Registration date and 1 year - php

I am trying to calculate the difference and output it like this:
"Your membership will be renewed in XXX days."
This is the code I am using ->
add_shortcode( 'membership', 'pren_info');
function pren_info() {
$pren = wp_get_current_user();
$first_name = $pren->first_name;
$last_name = $pren->last_name;
$date_format = 'j M Y H:i';
$today_obj = new DateTime( date( 'Y-m-d', strtotime( 'today' ) ) ); // Get today's Date Object
$register_date = get_the_author_meta( 'user_registered', get_current_user_id() ); // Grab the registration Date
$registered_obj = new DateTime( date( 'Y-m-d', strtotime( $register_date ) ) ); // Get the registration Date Object
$interval_obj = $today_obj->diff( $registered_obj ); // Retrieve the difference Object
$renewal_date = date('Y-m-d',strtotime('+1 year',$register_date));
$datediff = floor(strtotime($renewal_date)/(60*60*24)) - floor(strtotime($register_date)/(60*60*24));
echo '<div class="pren-hello"><b>Hi '.$first_name.'!</b></div>';
if( $interval_obj->days > 1 ) { // The most commonly hit condition at the top
echo __( "Your account was registered {$interval_obj->days} days ago as a member.", "theme" );
} elseif( 0 == $interval_obj->days ) { // IF they registered today
echo __( 'Your account was registered today.', 'theme' );
} elseif( 1 == $interval_obj->days ) { // IF they registered yesterday
echo __( 'Your account was registered yesterday.', 'theme' );
} else { // The off-chance we have less than zero
echo __( 'Please come back tomorrow for an update.', 'theme' );
}
echo '<div class="pren-info">In '.$datediff.' days, your membership needs to be renewed.</div>';
}
The shortcode works in terms of showing the name and showing how many days ago the user got registered, but what I cannot get working is this:
I need to calculate the time of "1 year from the date the user registered and the difference in days between that date and the date they registered".
This is "hard" to explain :)
Does it make sense?

I'm not sure that I got your question right.
You need to calculate interval to a future date, is that you case?
If so you can use DateInterval:
$date = new DateTime();
$date->add(new DateInterval('P1Y'));

You can use this to calculate the difference between two dates. It will return an integer.
function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval->format($differenceFormat);
}

Related

PHP: determination of the date minus weekends and holidays

There is a WordPress and ACF field with a date in the format 2022-04-30. From this date need to calculate 2 other dates, -2 days and +25 days. The problem is that it is necessary to take into account only working days, i.e. check weekends and holidays.
For example, we set the date May 3, 2022, which is Tuesday. From this date, I need to subtract 2 days, i.e. May 1, 2022, but this is Sunday, so we have to return to the first working day before May 1, i.e. Friday April 29, 2022. It's the same with holidays.
At the moment I have this code:
$setDate = get_field('set_date'); // ACF field, set May 3, 2022 (2022-05-03)
$offDate = wp_date('j F Y', strtotime('-2 days', strtotime($setDate)));
echo $offDate; // returns Sunday, May 1, 2022
I found holidays and weekends in json https://github.com/d10xa/holidays-calendar/blob/master/json/consultant2022.json
So I need to compare the given date with the dates from json and if there is a match, then minus one day and check the received date again. If there is a match, again minus one day and so on until no matches are found. Am I thinking correctly and can you tell me how to implement it? I am a very bad programmer, but there is a task)
At the moment I was only able to compare the dates and return the result found/not found. But I can't figure out how to take days off on the basis of this and send it for verification again(
$setDate = '2022-05-01';
$file = file_get_contents('https://raw.githubusercontent.com/d10xa/holidays-calendar/master/json/consultant2022.json', true);
$data = json_decode($file);
$found = array_search($setDate, $data->holidays);
if ($found === False) {
echo 'Not Found';
} else {
echo 'found';
}
The following has been tested on a few dates and I think it works as it should.
/*
JSON file is saved locally to a sub-directory
for the current working script directory.
This is to avoid unneccessary hits to the
remote site.
*/
$format='Y-m-d';
$url='https://raw.githubusercontent.com/d10xa/holidays-calendar/master/json/consultant2022.json';
$setDate = '2022-05-01';
$filepath=sprintf('%s/json/%s', __DIR__, basename( $url ) );
if( !file_exists( $filepath ) ){
file_put_contents( $filepath, file_get_contents( $url ) );
}
# read the file and generate JSON
$json=json_decode( file_get_contents( $filepath ) );
$hols=$json->holidays;
# create the initial DateTime object and find which weekday we are dealing with
# where 1 (for Monday) through 7 (for Sunday)
$obj=new DateTime( $setDate );
$date=$obj->format( $format );
$day=$obj->format('N');
# Is the given date a holiday/weekend?
if( array_search( $date, $hols ) ){
if( $day > 5 ){
# Date is either Sat or Sun... go back to previous working day
$subtract = 2 - ( 7 - $day );
$int=new DateInterval( sprintf('P%sD', $subtract ) );
$obj=new DateTime( $setDate );
$previous=$obj->sub( $int );
}else{
$previous=$obj->sub( new DateInterval('P2D') );
}
# create the future date ( add 25 days )
$int=new DateInterval('P25D');
$obj=new DateTime( $setDate );
$future=$obj->add( $int );
if( array_search( $future->format( $format ), $hols ) ){
# Future date is a holiday... go back to previous working day
$day=$future->format('N');
$subtract = 2 - ( 7 - $day );
$int=new DateInterval( sprintf('P%sD',$subtract ) );
$future=$future->sub( $int );
}
}else{
# Given date is NOT a holiday...
# take a copy of the original DateTime object for generating future date.
$ref=new DateTime( $setDate );
$int=new DateInterval( 'P2D' );
$previous=$obj->sub( $int );
$day=$previous->format('N');
# Is this a holiday?
if( $day > 5 ){
# yes - go back to previous working day
$subtract = 2 - ( 7 - $day );
$int=new DateInterval( sprintf('P%sD',$subtract ) );
$previous=$previous->sub( $int );
}
$int=new DateInterval('P25D');
$future=$ref->add( $int );
$day=$future->format('N');
# Is this a holiday?
if( $day > 5 ){
$subtract = 2 - ( 7 - $day );
$int=new DateInterval( sprintf('P%sD',$subtract ) );
$future=$future->sub( $int );
}
}
printf(
'<pre>
Given date: %s
Previous (-2): %s
Future (+25): %s
</pre>',
$date,
$previous->format( $format ),
$future->format( $format )
);
Which yields:
Given date: 2022-05-01
Previous (-2): 2022-04-29
Future (+25): 2022-05-26

How can I use a variable in a date diff function?

I am using an ACF Field to allow a client to content manage a countdown to their next event I am using JS flip clock on the desktop version but as it isn't responsive, I decided to use date diff to echo out just the number of days for mobile.
The site is currently live at theindustrialproject.co.uk
The code I currently have is this:
<?php
$date1 = date_create(date());
$date2 = date_create(the_field('mobile_date'));
$diff = date_diff($date1,$date2);
$difference = $diff;
if ($difference < 0) { $difference = 0; }
echo '<span class="countdown-mobile">'. floor($difference/60/60/24)."</span><br />";
if ($difference == 1) { echo "<p>Day</p>"; }
else { echo "<p>Days</p>"; }
?>
but it always returns 0. For reference, I pulled the code from here
Without knowing what the function the_field('mobile_date') will return ( either a date or timestamp? ) you might need to alter that particular line below but you should be able to use the DateTime object and format the difference like this
$format='Y-m-d';
$timezone=new DateTimeZone('Europe/London');
/* We need 2 datetime objects - one for now the other for the future date */
$now=new DateTime( date( $format, strtotime('now') ), $timezone );
$target=new DateTime( the_field('mobile_date'), $timezone );
/* Format the difference in days */
$days = $now->diff( $target )->days;
echo "<span class='countdown-mobile'>{$days}</span><br />" . ( $days == 1 ? '<p>Day</p>' : '<p>Days</p>' );

Get seconds between two dates and display it with human_time_diff()

I want to calculate seconds between two dates and display the purchased x seconds,minutes,hours ago text on my WooCommerce page.
I have this function:
$t_time = get_the_time( __( 'd/m/Y g:i:s', 'woocommerce' ), $order->ID );
/* $gmt_time = strtotime( $post->post_date_gmt ); */
$t_timestamp = strtotime ($t_time);
date_default_timezone_set('Europe/Budapest');
$ido = date('d/m/Y g:i:s');
$current_time = strtotime(date('d/m/Y g:i:s'));
//$current_time = strtotime(date('d/m/Y g:i:s'));
$time_diff = $current_time - $t_timestamp;
if ( $time_diff > 0 && $time_diff < 24*60*60 )
$h_time = sprintf( __( '%s ago', 'woocommerce' ), human_time_diff( $t_timestamp, $current_time ));
else
$h_time = get_the_time( $date_format, $order->ID );
}
Which outputs:
HTIME: 2014. szeptember 12.
time_diff: -2809
ido: 12/09/2014 5:36:17
t_time: 12/09/2014 5:23:06
current_time: 1418099777
t_timestamp: 1418102586
HTIME: 2 óra ago
gmt_time:
time_diff: 5891
ido: 12/09/2014 5:36:17
t_time: 12/09/2014 3:58:06
current_time: 1418099777
t_timestamp: 1418093886
My question is: How can be the current time smaller then the purchase date? In my opinion 12/09/2014 5:36:17 is bigger than 5:23:06.
Every help is appreciated :)
I have tried DateTime object, but if I add it, my jQuery is corrupted, and some parts of page doesn't load. There are an Uncaught TypeError errors.
I have solved the problem with the help of this code snippet.
http://www.intechgrity.com/calculate-the-difference-between-two-dates-in-php-using-php-5-3-oop-or-5-2-procedural/

WordPress: if post time is after a specific date

I'm trying to add to this if statement another one that checks if post time is before a specific date (let's say 14th March 2014..).
<?php if (in_category('5')) {
echo 'something'; }
?>
I tried with this but it's echoed even on posts newer than that date
<?php
$date1 = "2014-03-14";
$date2 = $post->post_date;
if ( (in_category('5')) && ($date1 < $date2) ) {
echo 'something';
}
?>
I'd convert your dates to timestamps first to make them easier to compare.
global $post;
$compare_date = strtotime( "2014-03-14" );
$post_date = strtotime( $post->post_date );
if ( in_category(5) && ( $compare_date > $post_date ) ) ...
It looks like you have your operator the wrong way round as well. You wanted to check if posts are before the date. The post date would have to be smaller to be before. Also you're passing in category ID 5 as a string for some reason which I corrected in my code above.
Thanks to Nathan, his answer worked great for me.
global $post;
$compare_date = strtotime( "2016-07-14" );
$post_date = strtotime( $post->post_date );
if ( in_category(2) && ( $compare_date >= $post_date ) ) {
echo "On or before July 14."
} else {
echo "After July 14."
}

Trouble calculating and displaying days left in PHP

I have two variables stored in my database containing the following data:
$date_published = 2012-05-04 00:00:00; //Straight from DB datetime field
$advert_duration = 15;
I want to show an advert for 15 days from the date it was published. To do so I need to work out the time difference.
I have read various places online about calculating time difference and have come up with the below code
In my attempt to work out the equation I can't seem to calculate the differences between $now - the date today, the $date_published and the $advert_duration. I can't get the correct result:
function days_left($date_published, $advert_duration){
$date = new DateTime($date_published);
$now = new DateTime();
$days_elapsed = $date->diff($now)->format("%d");
$days_left = $advert_duration - $days_elapsed;
return $days_left;
}
function getDaysLeft( $date, $duration )
{
// create $date and modify it by $duration
$date = new DateTime( $date );
$date->modify( sprintf( '+%d days', $duration ) );
// calculate the difference
$now = new DateTime();
$daysElapsed = (int) $now->diff( $date )->format( '%a' );
// set to negative value, if modified $date is before $now
if( $date < $now )
{
$daysElapsed = $daysElapsed * -1;
}
return $daysElapsed;
}
var_dump(
getDaysLeft( '2012-05-04 00:00:00', 15 ),
getDaysLeft( '2012-07-04 00:00:00', 15 )
);
If you're fetching your ad from the database, you can simply use a date function to calculate this :
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) >= date
Or you can do this in PHP (you'll get an UNIX timestamp) :
$date = strtotime('+15 days', strtotime($date_published));

Categories