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

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/

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

WooCommerce Conditional Delivery Notice based on weekdays and time

Based on Conditional Delivery Notice based on Time and Date in Woocommerce answer code, I'm trying to display a shipping message with the following lightly modified code:
I try this code without finding the result I hope :
add_action( 'woocommerce_before_customer_login_form', 'next_day_delivery' );
add_action( 'woocommerce_before_customer_login_form', 'next_day_delivery' );
add_action( 'woocommerce_before_checkout_form', 'next_day_delivery' );
add_action( 'woocommerce_before_shop_loop', 'next_day_delivery' );
add_action( 'woocommerce_before_single_product_summary', 'next_day_delivery' );
add_action( 'woocommerce_before_cart', 'next_day_delivery' );
function next_day_delivery() {
if( WC()->cart->is_empty() )
return; // Exit
// Set the time zone
date_default_timezone_set('Europe/Paris');
// From Monday to Thursday
$is_week_days = in_array( date('w'), array( 3, 4, 5, 6, 0 ) ) ? true : false;
$is_monday = date('w') == 1 ? true : false; // Monday
$is_tuesday = date('w') == 2 ? true : false; // Tuesday
$end_time = mktime('21', '00', '00', date('m'), date('d'), date('Y'));
$now_time = time();
$after_tomorow = date('l', strtotime('+2 days'));
$dateDiff = intval(($end_time - $now_time)/60);
$diff_hours = intval($dateDiff/60);
$diff_minutes = $dateDiff%60;
$hours_label = _n( 'heure', 'heures', $diff_hours, 'wooocommerce' );
$minutes_label = _n( 'minute', 'minutes', $diff_minutes, 'wooocommerce' );
if ( $is_monday && $now_time or $is_tuesday && $now_time < $end_time ) {
// print the information notice
$message = sprintf( __( '%s left to be delivered tomorrow!', 'woocommerce' ),
$diff_hours.' '.$hours_label.' and '.$diff_minutes.' '.$minutes_label);
}
elseif ( $end_time <= $now_time && $is_week_days ) {
$message = sprintf( __( 'Your order will be delivered this %s.', 'woocommerce' ), $after_tomorow );
} else {
$message = __( 'Your order will be prepared and shipped next upcoming monday and delivered on tuesday.', 'woocommerce' );
}
wc_print_notice( $message, 'success' );
}
But I cannot make it work for my needs…
We deliver our product each thursday, friday and saturday in different local pickups. So I'd like to have the delivery message that uses the following logic :
the orders made each week before tuesday 9pm (21h00 in TimeZone Europe/Paris), it should say "%s left to be delivered from thursday !"
the orders made each week after tuesday 9pm (21h00 in TimeZone Europe/Paris), it should say "Your order will be prepared and shipped from next upcoming wednesday and delivered from next thursday."
Any help will be very much appreciated.

Calculate Days Between Registration date and 1 year

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);
}

Display next delivery day based on date time rules in Woocommerce products loop

I have the following code below that creates a line of text under all products on the home, category and related products pages, that says "GREATER CAPE TOWN AREA"…
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_products_loop', 20 );
function woocommerce_products_loop(){
global $product;
echo '<p class="deliveryline">' . __("GREATER CAPE TOWN AREA", "woocommerce") . '</p>';
}
I'd like to have a line of text above this that says "NEXT DELIVERY: " and then uses the following logic:
If it's a weekday BEFORE 12pm, it should say "TOMORROW"
If it's a weekday AFTER 12pm, it should say the name of the business day after tomorrow.
if it's a friday BEFORE 12pm it should say "MONDAY"
if it's a friday AFTER 12pm it should say "TUESDAY"
Basically, we offer next day delivery on weekdays, for orders placed before 12pm.
I have code for something similar that may work..
$now = new Zend_Date();
if (($now->get(Zend_Date::WEEKDAY_DIGIT) % 6 == 0)
|| ($now->isLater('17:00:00', Zend_Date::TIMES))
) {
$now->set(
strtotime('+1 weekday', $now->toString(Zend_Date::TIMESTAMP)),
Zend_Date::TIMESTAMP
);
}
echo $now->toString(Zend_Date::W3C);
I just need help please figuring out the correct maths for what I need (this code is based on same day if before 5pm), and then where do I place it within the original code?
Could someone please help with this complete code snippet? Ideally I want it to look like the attached image.
Desired result:
The following code will display dynamically the delivery day based on your time and dates specifications (You will have to set your shop time zone in the code):
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_products_loop', 20 );
function woocommerce_products_loop(){
global $product;
// Set Your shop time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set('Europe/Paris');
$is_week_days = in_array( date('w'), array( 1, 2, 3, 4 ) ) ? true : false; // From Monday to Thursday
$is_friday = date('w') == 5 ? true : false; // Friday
$is_week_end = in_array( date('w'), array( 0, 6 ) ) ? true : false; // Weekend days
$end_time = mktime('12', '00', '00', date('m'), date('d'), date('Y')); // 12h00
$now_time = time();
$after_tomorow = date('l', strtotime('+2 days'));
// Displayed day conditions
if( $is_week_days && $now_time < $end_time ) {
$displayed_day = __("TOMORROW", "woocommerce");
} elseif( $is_week_days && $now_time >= $end_time ) {
$displayed_day = strtoupper( date( 'l', strtotime('+2 days') ) );
} elseif( $is_friday && $now_time < $end_time ) {
$displayed_day = __("MONDAY", "woocommerce");
} elseif( ( $is_friday && $now_time >= $end_time ) || $is_week_end ) {
$$displayed_day = __("THUESDAY", "woocommerce");
}
// Dynamic text Output based on date and time
echo '<p class="deliveryline">' . __("NEXT DELIVERY: ", "woocommerce") . $displayed_day .
'<br>' . __("GREATER CAPE TOWN AREA", "woocommerce") . '</p>';
}
Code goes in function.php file of your active child theme (active theme). Tested and works.

PHP - readable date from negative long timestamp with custom base year

I've seen a number of questions and answers on StackOverflow covering the scenario where timestamps have been based on the Unix Epoch but have been struggling to combine the solutions and modify them into a working solution for the data and custom base year I've been supplied.
<?php
date_default_timezone_set( 'Europe/London' );
function TransformDate( $iTimeStamp ) {
/* Insert transform code here */
$dt = new DateTime( '#' . $iTimeStamp );
return $dt->format( 'Y-m-d H:i:s' );
}
/* These timestamps should be between Sep-2014 and Jan-2015 */
$aTest = array( '-1554460973', '-1554427073', '-1554142396', '-1554139421' );
foreach( $aTest as $i ) echo( $i . ' - ' . TransformDate( $i ) . "\r\n" );
The only information I have to help process these timestamps is that they are based on the year 2013, with 10 ticks per second, and the data was originally from a Microsoft Jet database (so I would imagine similar data storage types to Microsoft Access etc).
I have tried so many combinations of adding or substracting the strtotime result value of 2013-01-01 and 1899-12-30, and multiplying and dividing by 10 that I've simplylost track now. For example:
$iTimeStamp -= strtotime( '2013-01-01' );
$iTimeStamp += strtotime( '1899-12-30' );
$iTimeStamp = round( $iTimeStamp / 10 );
So far though the closest I've got though is dates in 2012, though the December 31st 14:38pm part of the the date could be right:
$iTimeSinceBase = ( $iTimeStamp - strtotime( '2013-01-01' )) / 86400;
$iTimeStamp = strtotime( '2013-01-01' ) + $iTimeSinceBase;
The output for which is:
-1554460973 = 2012-12-31 14:38:22
-1554427073 = 2012-12-31 14:38:22
-1554142396 = 2012-12-31 14:38:26
-1554139421 = 2012-12-31 14:38:26
At this point any assistance is welcome! Thank you.

Categories