PHP Conditional dates treatment - comparing times & dates - php

I want to make a condition for my function to work. This is the logic.
Booking closing is 12noon today.
If the current time is before closing time(say 11am today) then run function x. I need to set a time when booking closes and compare it to the current time.
$tz_object = new DateTimeZone('Africa/Kampala');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
$timeNow = $datetime->format('Y\-m\-d\ h:i:s');
$date = new DateTime();
$date->setTime(23,00);
$timeAllowed = $datetime->format('Y\-m\-d\ h:i:s');
if ($timeNow < $timeAllowed) {
function woo_add_cart_fee() {
global $woocommerce;
$woocommerce->cart->add_fee( __('Custom', 'woocommerce'), number_format(5) );
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
}

Comparing DateTime objects is easy. You do not need to convert the date time to a string.
// time when booking closes
$bookclose = new \DateTime();
$bookclose->setTimezone(new DateTimeZone('Africa/Kampala'));
$bookclose->setTime(12,0,0);
// fake a time that the booking is being made for testing
$bookingtime = new \DateTime();
$bookingtime->setTimezone(new DateTimeZone('Africa/Kampala'));
$bookingtime->setTime(11,59,59);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
echo ' ALLOWED'.PHP_EOL;
} else {
echo ' NOT ALLOWED'.PHP_EOL;
}
$bookingtime->setTime(12,0,0);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
echo ' ALLOWED'.PHP_EOL;
} else {
echo ' NOT ALLOWED'.PHP_EOL;
}
$bookingtime->setTime(12,0,1);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
echo ' ALLOWED'.PHP_EOL;
} else {
echo ' NOT ALLOWED'.PHP_EOL;
}
RESULTS:
Booking time is 19/01/2017 11:59:59 ALLOWED
Booking time is 19/01/2017 12:00:00 NOT ALLOWED
Booking time is 19/01/2017 12:00:01 NOT ALLOWED

Related

If else statement for PHP DateTime diff

I am using meta_box value (YmdHi) and current Date&time to print time difference. And this code work for me.
Now additionally i want to print Live when 2 hours left to start Event.
What mistake I 'm doing to print if or else currently this not work for me?
$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);
if ($sinceThen > 2 * HOUR_IN_SECONDS){
echo $sinceThen->d.'days';
echo $sinceThen->h.'hours';
echo $sinceThen->i.'minutes';
}
else{
echo 'LIVE';
}
$sinceThen is a DateInterval (that's what DateTime::diff() returns), so you're comparing a int with an object, which obviously gives you unexpected results. To get the difference in seconds, subtract both DateTime instances' timestamps (which you obtain with DateTime::getTimestamp()):
$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);
$sinceThenInSeconds = $then->getTimestamp() - $now->getTimestamp();
if ($sinceThenInSeconds > 2 * HOUR_IN_SECONDS){
echo $sinceThen->d.'days';
echo $sinceThen->h.'hours';
echo $sinceThen->i.'minutes';
}
else{
echo 'LIVE';
}

Event date and time not select in datepiker less then server time

User careate feture event using bootstrep datepiker
User select date and time greter then currant time
4.If user select date Event time is 04-09-14 11:55AM and server time is 04-09-14 11:60AM
after not valid date for create event.
I am Using this code.
$event_time =htmlentities($_REQUEST['date_piker']) ;
$server_time = htmlentities( date('m-d-y h:iA')) ;
echo 'Event time:- '. $event_time.'</br>';
echo 'Server Time:-'. $server_time;
if($event_time < $server_time)
{
echo 'Date and time is invalid';
}
else
{
echo 'Date and time is valid';
}
But It is not working. i need help.
You should use DateTime::createFromFormat
$event = DateTime::createFromFormat('m-d-y h:iA', '04-09-14 11:55AM');
$server = DateTime::createFromFormat('m-d-y h:iA', '04-09-14 11:00AM');
if($event < $server){
echo 'Date and time is invalid';
}else{
echo 'Date and time is valid';
}
why u didnt use timestamps? like this
<?php
$event_time = htmlentities($_REQUEST['date_piker']);
$eventTimeTimestamp = strtotime($event_time);
$serverTimeTimestamp = time();
$server_time = htmlentities(date('m-d-y h:iA', $serverTimeTimestamp));
echo 'Event time:- ' . $event_time . '</br>';
echo 'Server Time:-' . $server_time;
if ($eventTimeTimestamp < $serverTimeTimestamp) {
echo 'Date and time is invalid';
} else {
echo 'Date and time is valid';
}

PHP if based on current system date

Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg

Convert time and date from one time zone to another in PHP

Basically what I need is an script that, when provided with a time and a timezone can return the time in another time zone.
My main issues are:
Where to get the time offset from GMT from - is there a public database available for this?
How to also take into consideration the daylight saving time (DST) differences as well.
How to nicely wrap it all up inside an PHP class - or is there such a class already available?
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
found on DateTime Manual on php.net
EDIT:
Like Pekka said: The DateTime class exists from 5.2 on and there you first have to find out which of the methods are realy implemented and which one only exist from 5.3 on.
try this, it might help :)
function converToTz($time="",$toTz='',$fromTz='')
{
// timezone by php friendly values
$date = new DateTime($time, new DateTimeZone($fromTz));
$date->setTimezone(new DateTimeZone($toTz));
$time= $date->format('Y-m-d H:i:s');
return $time;
}
A bit description:
The function takes 3 inputs, time to convert, timezone to convert to, current timezone and returns the output in the specified format.
I know its late. For anyone who would want simple function to convert utc to any local time zone
function UTCTimeToLocalTime($time, $tz = '', $FromDateFormat = 'Y-m-d H:i:s', $ToDateFormat = 'Y-m-d H:i:s')
{
if ($tz == '')
$tz = date_default_timezone_get();
$utc_datetime = DateTime::createFromFormat($FromDateFormat, $time, new
DateTimeZone('UTC'));
$local_datetime = $utc_datetime;
$local_datetime->setTimeZone(new DateTimeZone($tz));
return $local_datetime->format($ToDateFormat);
}
echo UTCTimeToLocalTime('2015-07-01 13:30:00','America/Denver');
To convert from the given timezone to the desired timezone, we just have to add/subtract the difference of timezones (in SECONDS) to given timezone.
$my_timestamp = strtotime("2020-09-22 14:07:26");
/*
Convert timezones difference into seconds
from -7:00 to +5:30 have 12hrs and 30min difference
So in seconds, 12.5*60*60 is equaled to 45000 seconds
*/
$time_zone_difference = 45000;
//Use date function to get datetime in your desired formate
echo date("Y-m-d h:i:sa", $my_timestamp + time_zone_difference );
or we can write it like
Below given functions are for additional help.
Convert timezone differences in seconds, (which you can hardcode, if it is fixed throught the project):
function timezoneDifferenceInSec( $source_timezone, $required_timezone){
$a = explode(":",$source_timezone);
$b = explode(":",$required_timezone);
$c = (intval($a[0])*60+intval($a[1]))*60;
$d = (intval($b[0])*60+intval($b[1]))*60;
$diffsec =0;
if($c < $d)
$diffsec = $d-$c;
else
$diffsec = $c-$d;
return $diffsec;
}
//function call
$differenc = timezoneDifferenceInSec("-07:00", "+05:30");
Function to convert DateTime into required Timezone (if difference is known):
//datetime in String and timezone_differe is in int
function convertTimezone( $source_date_time, $timezone_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezone_diff_in_sec);
}
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);
Function to convert DateTime into required Timezone (if difference in seconds among the timezones is known):
example: Timestamp give is "2020-09-22 14:07:26".
Timezones difference in seconds id 4500; //ie from -07:00 to +05:30
// timestamp as in String and timezones_diff_in_sec is in int
function convertTimezone( $timestamp, $timezones_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezones_diff_in_sec);
}
Function call (
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);
Here i use this function for converting datetime into another timezone.
For best result if you convert your datetime into utc timezone and then convert into required timezone then it is better result for it.
function ConvertTimezoneToAnotherTimezone($time, $currentTimezone, $timezoneRequired) {
$dayLightFlag = false;
$dayLgtSecCurrent = $dayLgtSecReq = 0;
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d H:i:s");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecCurrent = -3600;
// }
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s ");
$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d H:i:s ");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecReq = +3600;
// }
date_default_timezone_set($system_timezone);
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
if ($dayLightFlag) {
$final_diff = $dayLgtSecCurrent + $dayLgtSecReq;
$date->modify("$final_diff seconds");
}
$timestamp = $date->format("Y-m-d H:i:s ");
return $timestamp;
}
Thank You.

How to refactor this conditional to avoid repetition?

This is part of an events page that can be filtered by date (using pre-defined date ranges or a date picker).
I want to avoid repeating the whole foreach ($days as $day_number)... etc. loop for every condition.
I guess that whole loop could be moved to a function, but I'm not sure how to implement it.
<?php
// open the db connection
$db = new wpdb('user', 'pass', 'db', 'server');
// $today = date('Y-m-d');
$today = '2009-06-21';
$tomorrow = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+1, date('Y')) );
$seven_days_ahead = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+6, date('Y')) );
$thirty_days_ahead = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+29, date('Y')) );
echo '<div class="column first">';
if ( ! empty($_REQUEST['date_range']) )
{
// user has chosen a date/range, show matching events
$date_range = mysql_real_escape_string($_REQUEST['date_range']);
switch( $date_range )
{
case 'all':
// code here
break;
case 'next_7_days':
// code here
break;
case 'next_30_days':
// code here
break;
default:
// code here
}
}
else
{
// no date selected, show todays events
$days = convert_date_to_day_number( $today );
foreach ( $days as $day_number )
{
$where = sprintf( 'WHERE e.day_id = %s', $day_number );
$events = get_events( $where );
if ($events)
{
echo '<table class="results">';
render_day( $day_number );
foreach ($events as $event)
{
render_event($event);
}
echo '</table>';
}
else
{
echo 'No events';
}
}
}
echo '</div> <!--/column-->';
function convert_date_to_day_number($date)
{
global $db;
$sql = "SELECT day_number FROM days WHERE day_date = '$date'";
$day_numbers = $db->get_results($sql);
foreach ($day_numbers as $key => $value)
{
$day_number[] = $value->day_number;
}
return $day_number;
}
function get_events($where)
{
global $db;
$sql = "SELECT
e.id,
TIME_FORMAT(e.start_time, '%H:%i' ) AS start_time,
e.x_prod_desc AS title,
-- e.title_en AS title,
p.name_en AS place,
et.name_en AS type,
w.week_number,
d.day_date AS start_date
FROM event AS e
LEFT JOIN place AS p ON p.id = e.place_id
LEFT JOIN event_type AS et ON et.id = e.event_type_id
LEFT JOIN days AS d ON d.id = e.day_id
LEFT JOIN week AS w ON w.id = d.week_id ";
$sql .= $where;
$events = $db->get_results($sql);
return $events;
}
function render_event($event)
{
$request_uri = $_SERVER['REQUEST_URI'];
$output = <<<EOD
<tr class="week-$event->week_number">
<td class="topic"></td>
<td class="time">$event->start_time</td>
<td class="summary">
$event->title
</td>
<td class="type">$event->type</td>
<td class="location">
<span class="addr">$event->place</span>
</td>
</tr>
EOD;
echo $output;
}
function render_day( $day_number )
{
global $db;
$sql = "SELECT
d.day_number,
DATE_FORMAT( d.day_date, '%W %e %M %Y' ) AS date,
DATE_FORMAT( d.day_date, '%b' ) AS month,
DATE_FORMAT( d.day_date, '%e' ) AS day
FROM days AS d
WHERE day_number = " . $day_number;
$day = $db->get_results($sql);
$day = $day[0];
$output = <<<EOD
<tr class="day">
<th colspan="5">
<em class="date">
<abbr class="dtstart" title="20090605T1806Z">
<span title="$day->date">
<span class="month">$day->month</span>
<span class="day">$day->day</span>
</span>
</abbr>
</em>
$day->date
<span class="event-day">Day $day->day_number</span>
</th>
</tr>
EOD;
echo $output;
}
?>
First, you may want to use strtotime for relative dates :
$today = '2009-06-21';
$tomorrow = date( 'Y-m-d', strtotime('+1 day') );
$seven_days_ahead = date( 'Y-m-d', strtotime('+7 days') );
$thirty_days_ahead = date( 'Y-m-d', strtotime('+30 day') );
// or +1 month (=> calendar month)
Second, you can set two variables with begin & end dates, then:
$date = $start_date; // 'Y-m-d' format
while( $date <= $end_date ) {
//code here or fill up a table with your days
// using $date
$date = date( 'Y-m-d', strtotime( '+1day', strtotime($date) ) );
}
Whenever working with dates in PHP, you should check strtotime.
Rather than querying the database once for every day, I would make a WHERE statement that fetched all events for the desired date range, and then send that to a render function which loops through every row in the result set and if the day is different from previous one, calls render_day() before calling render_event().
switch (/* input from user */) {
// Build a date range here.
// Resulting statement would be something like:
// WHERE event_date >= '2009-06-10' AND event_date < '2009-06-17'
}
$events = get_events($filter);
$prev_date = null;
foreach ($events as $event) {
if ($event->date != $prev_date) render_day($event->date);
render_event($event);
$prev_date = $event->date;
}
function generateEventsTable($dateStr)
{
$days = convert_date_to_day_number( $today );
foreach ( $days as $day_number )
{
$where = sprintf( 'WHERE e.day_id = %s', $day_number );
$events = get_events( $where );
if ($events)
{
echo '<table class="results">';
render_day( $day_number );
foreach ($events as $event)
{
render_event($event);
}
echo '</table>';
}
else
{
echo 'No events';
}
}
}
Call it like this:
generateEventsTable($today);
Wow! I've read it!
First of all use template engine (like smarty) or any other way to split your code and HTML. That's a bad idea to echo HTML from inside the functions.
I'm not sure but I think that using unix-timestamps in DB could simplify your data structure. The same is about php code. Read carefully about date/time functions in php manual, I think, you'll find a lot of interesting things...
Actually, as I see from your code using timestamps and templates will reduce your code to some line for fetching data and assigning it to template engine. PHP's "date()" function already has an option to return week numbe, day number in a week or in a year etc...
This is dummy exaple what could your code look like:
$begin = mktime(...);
$end = mktime(...);
$query = "
SELECT a,b,c
FROM events
WHERE ctime >= $begin AND ctime <= $end AND ...
";
$events = array();
while ($fetch = fetch_here(...))
{
$event = new MyEvent();
$event->loadDBFetch($fetch);
array_push($events, $event);
}
$tplEngine->assign('events', $events);
Sure, this is not a ready-to-go solution, but it seems to me, that your code could be similar to this.

Categories