Using WooCommerce Bookings plugin, I'm developing a system where I have to compare two dates with PHP.
I have the next sql query to get this date:
$consulta2="SELECT meta_value FROM pwkynbjbwoocommerce_order_itemmeta WHERE meta_key='Fecha de Reserva' AND order_item_id=".$row["order_item_id"];
Fecha de Reserva give us a spanish date like septiembre 2016, or septiembre 1, 2016 (September 2016, or September 1,2016) for example.
I want to compare one date with "today", so I have tried to use this PHP code:
if (strtotime($row2["meta_value"])>time()){}
But it doesn't work.
How can I achieve this?
Thanks
Yes is it possible with this custom function where I list in an associative array the spanish month with numerical month as key, and I reorder the date to output it through strtotime() function. This function can also return the current time with 'now' as parameter.
This is the function code:
function bk_date( $date ) {
// Removing the coma (if there is a coma + a space)
$my_time = str_replace ( ',', '', $date );
// or replacing the coma by a space (if there is a coma alone without a space)
// $my_time = str_replace ( ',', ' ', $the_date );
$my_time_arr = explode( ' ', $my_time );
$my_time_count = count( $my_time_arr );
$month = $my_time_arr[0];
if ( count( $my_time_arr ) > 2 ) { // When there is the month, the day and the year
// Formating the day in 2 digits
$day = $my_time_arr[1] < 10 ? '0'.$my_time_arr[1] : $my_time_arr[1];
$year = $my_time_arr[2];
} else { // When there is the month, the day and the year
$year = $my_time_arr[1];
}
// Array of spanish month
$month_arr = array('01' => 'enero', '02' => 'febrero', '03' => 'marzo', '04' => 'abril', '05' => 'mayo', '06' => 'junio', '07' => 'julio', '08' => 'agosto', '09' => 'septiembre', '10' => 'octubre', '11' => 'noviembre', '12' => 'diciembre');
// Browse the list of month and compare (when $value match, it's replace by the index $key
foreach ( $month_arr as $key => $value ) {
if ( $month == $value ) {
$month = $key;
break;
}
}
if ( count( $my_time_arr ) > 2 )
$result = $year . '-' . $month . '-' . $day;
else
$result = $year . '-' . $month;
return $date == 'now' ? strtotime( $date ) : strtotime( $result );
}
This code goes on function.php file of your active child theme or theme.
As I don't really know if the date is like septiembre 1, 2016 or like septiembre 1,2016 (without a space after the coma), you will find a commented alternative in the code above.
My code work also for febrero, 2016 or febrero 2016 date format.
Please check that I haven't make any mistakes in the month names located in $month_arr array…
Usage:
echo bk_date($row2["meta_value"]); // display the timestamp of your spanish date.
// Comparing 2 timestamps (bk_date('now') return the "current time").
if ( bk_date($row2["meta_value"]) > bk_date('now') ) {
// do something
}
Related
How can I get the Financial Year date range in PHP like below when I pass year and return date range of every year start and end.
Like Eg.
Input Array = [2017,2018]
Financial Start Month = 04
Output Array =
[
'2017' => [
'start' => '2016-04-01',
'end' => '2017-03-31'
],
'2018' => [
'start' => '2017-04-01',
'end' => '2018-03-31'
]
]
My Effort:-
$year_arr = [2017,2018];
$fn_month = 04;
$date_range_arr = [];
foreach ($year_arr as $key => $value) {
$fn_start_date_year = ($value - 1);
$fn_start_date_month = $fn_month;
$fn_start_date_day = '01';
$fn_start_date_string = $fn_start_date_year.'-'.$fn_start_date_month.'-'.$fn_start_date_day;
$start_date = date('Y-m-d',strtotime($fn_start_date_string));
$fn_end_date_year = ($value);
$fn_end_date_month = (fn_month == 1)?12:(fn_month-1);
$fn_end_date_day = date('t',strtotime($fn_end_date_year.'-'.$fn_end_date_month.'-01'));
$fn_start_date_string = $fn_end_date_year.'-'.$fn_end_date_month.'-'.$fn_end_date_day;
$end_date = date('Y-m-d',strtotime($fn_start_date_string));
$date_range_arr[$value] = [
'start_date' => $start_date,
'end_date' => $end_date
];
}
Above is my effort. It is working perfectly but needs a more robust code.
A good way to manipulate dates in PHP is using the DateTime class. Here's an example of how to get the results you want using it. By using the modify method, we can avoid worries about complications like leap years (see the result for 2016 below).
$year_arr = [2016,2017,2018];
$fn_month = 03;
foreach ($year_arr as $year) {
$end_date = new DateTime($year . '-' . $fn_month . '-01');
$start_date = clone $end_date;
$start_date->modify('-1 year');
$end_date->modify('-1 day');
$date_range_arr[$year] = array('start_date' => $start_date->format('Y-m-d'),
'end_date' => $end_date->format('Y-m-d'));
}
print_r($date_range_arr);
Output:
Array (
[2016] => Array (
[start_date] => 2015-03-01
[end_date] => 2016-02-29
)
[2017] => Array (
[start_date] => 2016-03-01
[end_date] => 2017-02-28
)
[2018] => Array (
[start_date] => 2017-03-01
[end_date] => 2018-02-28
)
)
Demo on 3v4l.org
Maybe this is what you need?
I use strtotime to parse the date strings.
$year_arr = [2017,2018];
$fn_month = 04;
$date_range_arr = [];
foreach($year_arr as $year){
$date_range_arr[$year] =['start' => date("Y-m-d", strtotime($year-1 . "-" .$fn_month . "-01")),
'end' => date("Y-m-d", strtotime($year . "-" .$fn_month . "-01 - 1 day"))];
}
var_dump($date_range_arr);
Output:
array(2) {
[2017]=>
array(2) {
["start"]=>
string(10) "2016-04-01"
["end"]=>
string(10) "2017-03-31"
}
[2018]=>
array(2) {
["start"]=>
string(10) "2017-04-01"
["end"]=>
string(10) "2018-03-31"
}
}
https://3v4l.org/nMUHt
Try this snippet,
function pr($a)
{
echo "<pre>";
print_r($a);
echo "</pre>";
}
$year_arr = [2017, 2018];
$fn_month = 4;
$date_range_arr = [];
foreach ($year_arr as $key => $value) {
$fn_month = str_pad(intval($fn_month),2, 0, STR_PAD_LEFT);
$date = "".($value-1)."-$fn_month-01"; // first day of month
$date_range_arr[$value] = [
'start_date' => $date,
'end_date' => date("Y-m-t", strtotime($date.' 11 months')), // last month minus and last date of month
];
}
pr($date_range_arr);
die;
str_pad - Pad a string to a certain length with another string
Here is working demo.
I am working on a snippet for displaying opening hours and it works fine in english language and when I change the keys of array to another language it doesn't hyphenate the letters instead it does separation by comma.
What am I doing Wrong?
Below is the PHP code with 2 arrays with 1 commented which is in english and which works fine. Another is an italian langugage weekdays
<?php
/*
// english weekdays
$openHours = array(
'Mon' => '9am-7pm',
'Tue' => '9am-7pm',
'Wed' => '9am-7pm',
'Thu' => '9am-10pm',
'Fri' => 'closed',
'Sat' => '9am-10pm',
'Sun' => '9am-10pm'
);
*/
// italian weekdays
$openHours = array(
'lunedì' => '9am-7pm',
'martedì' => '9am-7pm',
'mercoledì' => '9am-7pm',
'giovedì' => '9am-10pm',
'venerdì' => 'closed',
'sabato' => '9am-10pm',
'domenica' => '9am-10pm'
);
$new_array = array();
foreach($openHours as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
foreach ($new_array as $days=>$time){
$daylist = explode(',',$days);
if ($time!='closed'){
if (count($daylist)>2){
$limit = count($daylist)-1;
$first = $daylist[0];
$last = $daylist[$limit];
//loop will go here.
if (date('D', strtotime('+'.$limit.' days', strtotime($first)))==$last){
echo $first.'-'.$last.' '.$time.'<br>';
} else {
$sep = '';
foreach ($daylist as $sepdays){
echo $sep.$sepdays;
$sep = ',';
}
echo ' '.$time.'<br>';
}
} else {
echo $days.' '.$time.'<br>';
}
} else {
$daylist = explode(',',$days);
foreach ($daylist as $sepdays){
echo $sepdays.' '.$time.'<br>';
}
}
}
?>
RESULT
Current Result what am getting with italian language.
lunedì,martedì,mercoledì 9am-7pm
venerdì closed
giovedì,sabato,domenica 9am-10pm
Expected RESULT
This is what I'm expecting.
lunedì-mercoledì 9am-7pm
venerdì closed
giovedì,sabato,domenica 9am-10pm
You are using your array's keys within date and strtotime functions to do your comparisons, both functions works for English. If you need to do it on other languages you should use setlocale and strftime, it will be a lot more complicated process. My suggestions:
Use numeric representation of the days of the week (0-6) and on display, replace the number with the value for the desired language.
Use multidimensional arrays including the numeric day of the week and the opening hours.
I have an array with dates. ie.
array(
0 => '2016-08-01',
1 => '2016-07-15',
2 => '2016-07-01'
);
I need to get the distinct months in array. ie.
array(
0 => 7,
1 => 8
);
I need it to do a foreach to show: June - Juy - August with the distinct months from the dates array. (That part I know how)
You can reformat the date using a combination of array_map, DateTime, and array_unique to achieve that result.
$arr = array(
0 => '2016-08-01',
1 => '2016-07-15',
2 => '2016-07-01'
);
$dates = array_unique(array_map(function($date) {
return DateTime::createFromFormat('Y-m-d', $date)->format('n');
}, $arr));
var_dump($dates);
array(2) {
[0]=>
string(1) "8"
[1]=>
string(1) "7"
}
Of course, it's important to note this results in two dates like 2015-08-11 and 2016-08-04 both showing up as one value in the array. So it's not entirely clear why you would want to do this, but this will meet your specified requirements.
This is the loop you need :
<?php
$arr = array( '2016-08-01',
'2016-07-15',
'2016-07-01' );
$months = array(); // EMPTY ARRAY FOR MONTHS.
foreach ( $arr as $date ) // VISIT EACH DATE IN ARRAY.
{ $mon = substr( $date,5,2 ); // EXTRACT THE MONTH DIGITS.
if ( ! in_array( $mon,$months ) ) // IF MONTH IS NOT IN ARRAY
array_push( $months,$mon ); // INSERT THE MONTH DIGITS.
}
var_dump( $months );
?>
Edit : display month name :
<?php
$arr = array( '2016-08-01',
'2016-07-15',
'2016-07-01' );
$months = array(); // EMPTY ARRAY FOR MONTHS.
foreach ( $arr as $date ) // VISIT EACH DATE IN ARRAY.
{ $mon = substr( $date,5,2 ); // EXTRACT THE MONTH DIGITS.
if ( ! in_array( $mon,$months ) ) // IF MONTH IS NOT IN ARRAY
{ array_push( $months,$mon ); // INSERT THE MONTH DIGITS.
echo date ("F",mktime( null,null,null,$mon,1 ) ); // ◄ MONTH NAME!!!
}
}
?>
Edit #2 : storing month names in array :
<?php
$arr = array( '2016-08-01',
'2016-07-15',
'2016-07-01' );
$months = array(); // EMPTY ARRAY FOR MONTHS.
foreach ( $arr as $date ) // VISIT EACH DATE IN ARRAY.
{ $mon = date("F",mktime( null,null,null,substr( $date,5,2 ),1 ) ); // EXTRACT MONTH.
if ( ! in_array( $mon,$months ) ) // IF MONTH IS NOT IN ARRAY
array_push( $months,$mon ); // INSERT MONTH NAME IN ARRAY.
}
var_dump( $months );
?>
Just use substr on each of your dates array entries to retrieve the chars 5 to 7, then store them in a new array :
$dates = array(
0 => '2016-08-01',
1 => '2016-07-15',
2 => '2016-07-01');
$months = array();
foreach ($dates as $date) {
$months[] = (int)substr($date, 5, 2);
}
$months = array_unique($months); // Remove duplicates
sort($months);
I'm looping through an array of days in the current month to generate another array of days that are on or after the current day. I'm also doing the same for the next month (which will always include all days as they are after the current date).
The complexity is when the next month is in a different year to the current month. The format of the final array is like this:
array("year" => array("month" => array(days)));
When both months are in the same year it might look like this:
$allDays = array("2013" => array( "11" => array(28,29,30), "12" => array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)));
When the 2 months are in different years (i.e. Dec and Jan) it might look like this:
$allDays = array("2013" => array("12" => array(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)), "2014" => array("1" => array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31) )) ;
Here's my code that generates the list of dates for the current month and the next month:
// Set the default timezone
date_default_timezone_set('Australia/Sydney');
// Get days for current month
$day = date("Y-m-d");
$i = strtotime($day);
array("year" => array("month" => array(days)));
$linked_days = array(
date('Y', $i) => array(
date('m') => range(date('d', $i), intval(date('t'))),
),
);
// Get days for next month
$day2 = date("Y-m-d", strtotime('first day of next month')) ;
$i2 = strtotime($day2);
array("year" => array("month" => array(days)));
$linked_days2 = array(
date('Y', $i2) => array(
date('m') => range(date('d', $i2), intval(date('t'))),
),
);
I'm not sure how to go about combining them into the 1 array with a different sytanx if they are in the same year or not?
You can check if there is already an entry for the year in your array with isset function :
Change this
$day2 = date("Y-m-d", strtotime('first day of next month')) ;
$i2 = strtotime($day2);
array("year" => array("month" => array(days)));
$linked_days2 = array(
date('Y', $i2) => array(
date('m') => range(date('d', $i2), intval(date('t'))),
),
);
To
$day2 = date("Y-m-d", strtotime('first day of next month')) ;
$i2 = strtotime($day2);
array("year" => array("month" => array(days))); //useless line ??
if(!isset($linked_days[date('Y', $i2)])){
//if no entry for this year in array, create new entry
$linked_days[date('Y', $i2)] = array(date('m') => range(date('d', $i), intval(date('t'))));
}
else{
//else, just add the month entry
$linked_days[date('Y', $i2)][date('m')] = range(date('d', $i2), intval(date('t'))) ;
}
Working with an array of dates (opening times for a business). I want to condense them to their briefest possible form.
So far, I started out with this structure
Array
(
[Mon] => 12noon-2:45pm, 5:30pm-10:30pm
[Tue] => 12noon-2:45pm, 5:30pm-10:30pm
[Wed] => 12noon-2:45pm, 5:30pm-10:30pm
[Thu] => 12noon-2:45pm, 5:30pm-10:30pm
[Fri] => 12noon-2:45pm, 5:30pm-10:30pm
[Sat] => 12noon-11pm
[Sun] => 12noon-9:30pm
)
What I want to achieve is this:
Array
(
[Mon-Fri] => 12noon-2:45pm, 5:30pm-10:30pm
[Sat] => 12noon-11pm
[Sun] => 12noon-9:30pm
)
I've tried writing a recursive function and have managed to output this so far:
Array
(
[Mon-Fri] => 12noon-2:45pm, 5:30pm-10:30pm
[Tue-Fri] => 12noon-2:45pm, 5:30pm-10:30pm
[Wed-Fri] => 12noon-2:45pm, 5:30pm-10:30pm
[Thu-Fri] => 12noon-2:45pm, 5:30pm-10:30pm
[Sat] => 12noon-11pm
[Sun] => 12noon-9:30pm
)
Can anybody see a simple way of comparing the values and combining the keys where they're similar? My recursive function is basically two nested foreach() loops - not very elegant.
Thanks,
Matt
EDIT: Here's my code so far, which produces the 3rd array above (from the first one as input):
$last_time = array('t' => '', 'd' => ''); // blank array for looping
$i = 0;
foreach($final_times as $day=>$time) {
if($last_time['t'] != $time ) { // it's a new time
if($i != 0) { $print_times[] = $day . ' ' . $time; }
// only print if it's not the first, otherwise we get two mondays
} else { // this day has the same time as last time
$end_day = $day;
foreach($final_times as $day2=>$time2) {
if($time == $time2) {
$end_day = $day2;
}
}
$print_times[] = $last_time['d'] . '-' . $end_day . ' ' . $time;
}
$last_time = array('t' => $time, 'd' => $day);
$i++;
}
I don't think there is a particularly elegant solution to this. After much experimenting with the built in array_* functions trying to find a nice simple solution, I gave up and came up with this:
$lastStart = $last = $lastDay = null;
$new = array();
foreach ($arr as $day => $times) {
if ($times != $last) {
if ($last != null) {
$key = $lastStart == $lastDay ? $lastDay : $lastStart . '-' . $lastDay;
$new[$key] = $last;
}
$lastStart = $day;
$last = $times;
}
$lastDay = $day;
}
$key = $lastStart == $lastDay ? $lastDay : $lastStart . '-' . $lastDay;
$new[$key] = $last;
It only uses one foreach loop as opposed to your two, as it keeps a bunch of state. It'll only merge adjacent days together (i.e., you won't get something like Mon-Tue,Thu-Fri if Wednesday is changed, you'll get two separate entries).
I'd approach it by modelling it as a relational database:
day start end
1 12:00 14:45
1 17:30 22:30
...
Then its fairly easy to reduce - there are specific time intervals:
SELECT DISTINCT start, end
FROM timetable;
And these will occur on specific days:
SELECT start, end, GROUP_CONCAT(day) ORDER BY day SEPERATOR ','
FROM timetable
GROUP BY start,end
(this uses the MySQL-only 'group_concat' function - but the method is the same where this is not available)
would give:
12:00 14:45 1,2,3,4,5
17:30 22:30 1,2,3,4,5
12:00 23:00 6
12:00 21:30 7
Then it's fairly simple to work out consecutive date ranges from the list of days.
C.
As an alternative, I managed to cobble together a version using array_* functions. At some point though, 'elegance', 'efficiency' and 'readability' all packed up and left. It does, however, handle the edge cases I mentioned in the other answer, and it left me with a nice warm glow for proving it could be done in a functional manner (yet at the same time a sense of shame...)
$days = array_keys($arr);
$dayIndices = array_flip($days);
var_dump(array_flip(array_map(
function ($mydays) use($days, $dayIndices) {
return array_reduce($mydays,
function($l, $r) use($days, $dayIndices) {
if ($l == '') { return $r; }
if (substr($l, -3) == $days[$dayIndices[$r] - 1]) {
return ((strlen($l) > 3 && substr($l, -4, 1) == '-') ? substr($l, 0, -3) : $l) . '-' . $r;
}
return $l . ',' . $r;
}, '');
}, array_map(
function ($day) use ($arr) {
return array_keys($arr, $arr[$day]);
}, array_flip($arr)
)
)));
I tested it with this input:
'Mon' => '12noon-2:45pm, 5:30pm-10:30pm',
'Tue' => '12noon-2:45pm, 5:30pm-10:30pm',
'Wed' => '12noon-2:45pm, 5:30pm-10:00pm',
'Thu' => '12noon-2:45pm, 5:30pm-10:30pm',
'Fri' => '12noon-2:45pm, 5:30pm-10:00pm',
'Sat' => '12noon-2:45pm, 5:30pm-10:30pm',
'Sun' => '12noon-9:30pm'
And got this:
["Mon-Tue,Thu,Sat"]=> string(29) "12noon-2:45pm, 5:30pm-10:30pm"
["Wed,Fri"]=> string(29) "12noon-2:45pm, 5:30pm-10:00pm"
["Sun"]=> string(13) "12noon-9:30pm"
Basically, the array_map at the end transforms the input into an associative array of times to an array of days that they occur on. The large block of code before that reduces those days into a nicely formatted string using array_reduce, consulting the $days and $dayIndices arrays to check if days are consecutive or not.