I have an array with timestamps. If this timestamps are between two given dates I need to collect them into another array.
Let me use an example:
Lets say $array1[] has:
Array ( [0] => 1299147500 [1] => 1299147453 [2] => 1299146476 [3] => 1299143220 [4] => 1297934349 [5] => 1297845742 [6] => 1297695551 [7] => 1296134251 [8] => 1295948452 [9] => 1295554308 [10] => 1295369389 [11] => 1295345559 [12] => 1295261432 [13] => 1295014784 [14] => 1294929846 [15] => 1294832875 )
I need to create $array2[] with those values from $array1[] that are between Thursday February 17, 2011 and Thursday March 3, 2011
How can I do this?
Thanks a ton
$low = strtotime('Thursday February 17, 2011');
$high = strtotime('Thursday March 3, 2011');
$array2 = array();
foreach($array1 as $timestamp) {
if ($low <= $timestamp && $timestamp <= $high) {
$array2[] = $timestamp;
}
}
an alternative using array_filter which will maintain the keys.
$low = strtotime('Thursday February 17, 2011');
$high = strtotime('Thursday March 3, 2011');
$array2 = array_filter($array1, function($timestamp) use ($low, $high) {
return $low <= $timestamp && $timestamp <= $high;
});
Convert first and last date to timestamps using strtotime()
For each item in the array, if it is between min and max, copy it to the second array.
Sort the array of timestamps
http://codepad.org/mDvRJ534
<?php
$array1 = array(1299147500,1299147453,1299146476,1299143220,1297934349,1297845742,1297695551,1296134251,1295948452,1295554308,1295369389,1295345559,1295261432,1295014784,1294929846,1294832875);
$array2 = array();
$date1 = strtotime('Thursday February 17, 2011');
$date2 = strtotime('Thursday March 3, 2011');
foreach($array1 as $timestamp){
if($timestamp <= $date2 && $timestamp >= $date1)
$array2[] = $timestamp;
}
echo 'date1 = '.$date1."\n";
echo 'date2 = '.$date2."\n";
print_r($array2);
Someone answered this in another post over here mate How to check if a date is in a given range?
Related
I am trying to generate the range of days, from 1 to 28, with the English ordinal suffix for the day of the month. For example: 1st of month, 2nd of month...
for($i = 1; $i <= 28; $i++)
{
$arrayRange[] = date('dS', strtotime($i));
}
echo "<pre>";
print_r($arrayRange);
echo "</pre>";
Output:
Array
(
[0] => 01st
[1] => 01st
[2] => 01st
...
[26] => 01st
[27] => 01st
)
What am I doing wrong..?
You should pass correct timestamp as the second parameter of date function and use j (without leading zero) day format:
list($m, $y) = explode('-', date('m-Y'));
for($d = 1; $d <= 28; $d++)
{
$arrayRange[] = date('jS', mktime(0, 0, 0, $m, $d, $y));
}
echo "<pre>";
print_r($arrayRange);
echo "</pre>";
Try this, it uses the contextual date functionality of '+1 day' etc to register your integer as a day :)
To answer your second question - as in what you're doing wrong - you're passing an integer to a function that expects a string.
<?php
for($i = 0; $i <= 27; $i++)
{
//The February is there to keep '1st' a '1st' even on days when it's not
//the '31st'
$arrayRange[] = date('dS', strtotime("1st february +".$i.' day'));
}
echo "<pre>";
print_r($arrayRange);
echo "</pre>";
Output:
Array
(
[0] => 01st
[1] => 02nd
...
[28] => 28th
)ยจ
Edit:
To remove the 0s, you can use ltrim() like this:
$arrayRange[$i] = ltrim(date('dS', strtotime("1st february +".$i.' day')), "0");
Which will give you an output like this
[0] => 1st
[1] => 2nd
...
[28] => 28th
Edit 2:
Fixed it. Props to MLF for noticing the mistake.
You can use something like this:
$arrayRange[] = (new DateTime('Aug '.$i))->format('jS');
I need to add days (input type number + input type date) but the result must be an array so I can INSERT one after another into the Database.
Here's the code (After HTML Form submitted):
<?php
$start_date = '2017-12-22';
$duration = '3';
$d = new DateTime($start_date);
$t = $d->getTimestamp();
// loop for X days
for($i=0; $i <= $duration; $i++){
// add 1 day to timestamp-
$addDay = 86400;
// get what day it is next day
$nextDay = date('w', ($t + $addDay));
// if it's Saturday or Sunday get $i-1
if($nextDay === 6 || $nextDay === 7) {
$i --;
}
// modify timestamp, add 1 day
$t = $t + $addDay;
$d->setTimestamp($t);
$day_off = $d->format( 'Y-m-d' ). "<br />";
echo $day_off;
$query = "INSERT SQL";
}
?>
From echo $day_off result I get:
2017-12-23
2017-12-24
2017-12-25
2017-12-26
Instead of 23, 24, 25, 26. I need to get the result below:
2017-12-22
2017-12-25
2017-12-26
2017-12-27
22 is the input date, start from 25 because 23 and 24 are Sat and Sun and weekends need to be excluded.
How can I achieve this result? I've been searching on the net but unfortunately, I couldn't find what I needed.
#C. Geek answer made it to works, but I have a more complex question here, since my account are not eligible to ask more question so I'll ask here.
So here's what I've tried so far (with #C. Geek answer) :
<?php
// loop for X days
for($i=0; $i < $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$day_off[] = $t;
foreach($day_off as $dayoff) {
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE `date` = '$dayoff' "));
}
$holiday[] = $data_holiday['date'];
$date = array_diff($day_off, $holiday);
$dayoff_ = $holiday;
?>
Start date : 2017-12-29
Duration : 5 days
From print_r($day_off); I'm getting this result :
Array ( [0] => 2017-12-29 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 ) Array ( [0] => 2017-12-29 [1] => 2018-01-01 [2] => 2018-01-02 )
And from print_r($holiday); I'm getting this result :
Array ( [0] => ) Array ( [0] => [1] => 2018-01-01 ) Array ( [0] => [1] => 2018-01-01 [2] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => ) Array ( [0] => [1] => 2018-01-01 [2] => [3] => [4] => )
The national date fetched from database is 2018-01-01 with 5 looping result, the final date result I need to make are 29 Dec, 02 Jan 03 Jan and 04 Jan, 05 Jan.
Any help will be much appreciated.
Thanks.
https://stackoverflow.com/a/4261223/6288442
If you are limiting to weekdays use the string weekdays.
echo date ( 'Y-m-j' , strtotime ( '3 weekdays' ) );
This should jump you ahead by 3 weekdays, so if it is Thursday it will
add the additional weekend time.
Source: http://www.php.net/manual/en/datetime.formats.relative.php
As for formatting:
http://php.net/manual/en/function.strftime.php
string strftime ( string $format [, int $timestamp = time() ] )
If you need more help with writing the code than these, please do tell in a comment
Here is my full answer:
$start_date = '2017-12-22';
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
$arr[]=$t;
}
Get the holidays before the looping, then in the loop, check if date is in_array before adding it to $arr.
e.g.
$start_date = '2017-12-22';
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `holiday_master_data` WHERE YEAR(`date`) BETWEEN YEAR('$start_date') AND YEAR('$start_date')+1 "));
$holidays =
$duration = 3;
$arr=null;
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = strftime("%Y-%m-%d",$d);
if(!in_array($t,$data_holiday))
$arr[]=$t;
}
FINALLY!! After several hours I fixed everything. Here's the code how I manage to skip (Sun and Monday) and also Skip the Holiday's fetched from the database (based on #C.Geek answers + several tweaking):
<?php
include 'conn.php';
$start_date = mysqli_real_escape_string($con, $_POST['start_date']);
$duration = mysqli_real_escape_string($con, $_POST['duration']);
// loop for X days
for($i=0; $i <= $duration; $i++){
$d = strtotime("$start_date +$i weekdays");
$t = explode(", ", strftime("%Y-%m-%d", $d));
foreach ($t as $date) {
$to_encode = array("date" => $date);
$date_where = $to_encode['date'];
$data_holiday = mysqli_fetch_array(mysqli_query($con, "SELECT `date` AS '0' FROM `holiday_master_data` WHERE DATE(`date`) BETWEEN DATE('$date_where') AND DATE('$date_where') + 1 GROUP BY `id` "));
$encode_holiday = array("date" => $data_holiday[0]);
break;
}
$holiday = array_unique($encode_holiday);
$dayoff = array_diff($t, $holiday);
foreach($dayoff as $date) {
$query = mysqli_query($con, "INSERT INTO ");
if ($query) {
echo "<script>alert('Absence Saved'); window.location ='document.php' </script>";
} else {
echo "<script>alert('Gagal'); window.location ='document.php' </script>";
}
}
}
?>
Hope this helps anyone seeking the same problem I had.
Cheers.
I want to store names of the week days in an array from given date range.
Eg. If given date range is from 2016-12-1 to 2017-02-22 then i want to store all weekdays comes in this date range.
$timestamp = strtotime('next Sunday');
$days = array();
for ($i = 0; $i < 7; $i++) {
$days[] = strftime('%A', $timestamp);
$timestamp = strtotime('+1 day', $timestamp);
}
Try this. Provide Start date,end date, weekdays as input params
function progDateRange($date, $end_date, array $wkDays, array $excluded)
{
$dates = array();
$current_date = strtotime($date);
$max_date = min(strtotime('+2 years'), strtotime($end_date));
$dow = array_keys($wkDays);
while ($current_date < $max_date) {
if ($excluded && in_array($date_formatted, $excluded, true)) {
continue;
}
if (in_array(date('l'), $dow, true)) {
array_push($dates, $date);
}
$current_date = strtotime('+1 day', $current_date);
$date = date('Y-m-d', $current_date);
}
return $dates;
}
The solution using date and strtotime functions:
$date_from = '2016-12-1';
$date_to = '2017-02-22';
$current = strtotime($date_from);
$max_time = strtotime($date_to);
$weekdays = [];
while ($current <= $max_time) {
// getting weekday name for current timestamp within date range
$weekdays[] = date('l', $current);
$current = strtotime('+1 day', $current); // setting timestamp for each next next day in increase order
}
print_r($weekdays);
The output will be like below:
Array
(
[0] => Thursday
[1] => Friday
[2] => Saturday
[3] => Sunday
[4] => Monday
[5] => Tuesday
[6] => Wednesday
[7] => Thursday
[8] => Friday
[9] => Saturday
[10] => Sunday
[11] => Monday
[12] => Tuesday
[13] => Wednesday
[14] => Thursday
....
...
I'm a new to PHP and don't know if my request is possible:
I'd need to get an array with the days of the current week and also indicate for each day if it's the first, second, third, fourth or fifth occurrence of that date for the month.
Examples
For the 1st week of August 2016, it would be:
monday1
tuesday1
wednesday1
thursday1
friday1
saturday1
sunday1
But for the last week of August 2016 (which begins in August and ends in September) it would be:
monday5
tuesday5
wednesday1
thursday1
friday1
saturday1
sunday1
I tried this, but it only works for the current day.
$week_of_the_month = ceil(date('d', $time)/7);
$jd = cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
echo jddayofweek($jd,1).$week_of_the_month;
$d = new DateTime();
$days = [];
for ($i = 0; $i < 7; $i++) {
$date = $d->format('j');
$days[$date] = $d->format('l - ') . ceil($date/7);
$d->add(new DateInterval('P1D'));
}
That will work for the current date, but you can test it on weeks that cross over two months by setting a specific date to work with:
$d = new DateTime('2016-08-31');
The result is as follows:
print_r($days);
Array
(
[31] => Wednesday - 5
[1] => Thursday - 1
[2] => Friday - 1
[3] => Saturday - 1
[4] => Sunday - 1
[5] => Monday - 1
[6] => Tuesday - 1
)
If you want the dates to always start on the Monday of the current week, the DateTime constructor allows you to pass in a string as such:
$d = new DateTime('monday this week');
Today is Thursday, but it gives:
Array
(
[1] => Monday - 1
[2] => Tuesday - 1
[3] => Wednesday - 1
[4] => Thursday - 1
[5] => Friday - 1
[6] => Saturday - 1
[7] => Sunday - 1
)
Changing Language
If you want to change the language of the date output, that is a separate topic (see here). You will need to have the locales/extensions installed on your system. If you don't want to go down that route, you could just map the days into your language yourself:
$intlDays = [
'Monday' => 'Lundi',
'Tuesday' => 'Mardi',
'Wednesday' => 'Mercredi',
'Thursday' => 'Jeudi',
'Friday' => 'Vendredi',
'Saturday' => 'Samedi',
'Sunday' => 'Dimanche'
];
$d = new DateTime('monday this week');
$days = [];
for ($i = 0; $i < 7; $i++) {
$date = $d->format('j');
$output = $d->format('l - ') . ceil($date/7);
$output = str_replace(array_keys($intlDays), $intlDays, $output);
$days[$date] = $output;
$d->add(new DateInterval('P1D'));
}
$start_date = "2013-05-01";
$last_date = "2013-08-30";
How can I get dates of tuesdays and thursdays between these two dates?
<?php
$start = new DateTime('2013-05-01');
$end = new DateTime('2013-08-30');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
if ($dt->format("N") == 2 || $dt->format("N") == 4) {
echo $dt->format("l Y-m-d") . "<br>\n";
}
}
See it in action
What this code does:
Creates a starting date object using DateTime.
Creates a starting date object using DateTime.
Creates a DateInterval object to represent our interval of time to iterate through. In this case 1 day.
Creates a DatePeriod object to manage these objects.
Using DatePeriod, it iterates through the date starting with the starting date and ending at the end date. We use DateTime::format() with the N parameter to get the day number of the week. If the day number of the week is 2 (Tuesday) or 4 (Thursday) echo out it's value.
Some PHP-Fu
$start_date = '2013-05-01';
$last_date = '2013-08-30';
$dates = range(strtotime($start_date), strtotime($last_date),86400);
$days = array('tuesday' => array(), 'thursday' => array());
array_map(function($v)use(&$days){
if(date('D', $v) == 'Tue'){
$days['tuesday'][] = date('Y-m-d', $v);
}elseif(date('D', $v) == 'Thu'){
$days['thursday'][] = date('Y-m-d', $v);
}
}, $dates); // Requires PHP 5.3+
print_r($days);
Output
Array
(
[tuesday] => Array
(
[0] => 2013-05-07
[1] => 2013-05-14
[2] => 2013-05-21
[3] => 2013-05-28
[4] => 2013-06-04
[5] => 2013-06-11
[6] => 2013-06-18
[7] => 2013-06-25
[8] => 2013-07-02
[9] => 2013-07-09
[10] => 2013-07-16
[11] => 2013-07-23
[12] => 2013-07-30
[13] => 2013-08-06
[14] => 2013-08-13
[15] => 2013-08-20
[16] => 2013-08-27
)
[thursday] => Array
(
[0] => 2013-05-02
[1] => 2013-05-09
[2] => 2013-05-16
[3] => 2013-05-23
[4] => 2013-05-30
[5] => 2013-06-06
[6] => 2013-06-13
[7] => 2013-06-20
[8] => 2013-06-27
[9] => 2013-07-04
[10] => 2013-07-11
[11] => 2013-07-18
[12] => 2013-07-25
[13] => 2013-08-01
[14] => 2013-08-08
[15] => 2013-08-15
[16] => 2013-08-22
[17] => 2013-08-29
)
)
Online demo
$start_date = strtotime("2013-05-01");
$last_date = strtotime("2013-08-30");
while ($start_date <= $last_date) {
$start_date = strtotime('+1 day', $start_date);
if (date('N',$start_date) == 2 || date('N',$start_date) == 4){
echo date('Y-m-d', $start_date).PHP_EOL;
}
}
<?php echo date('Y-m-d', strtotime('next thursday', strtotime($start_date)));
Also for tuesday ofcourse
Please use the following function for your solution,
function daycount($day, $startdate, $lastdate, $counter=0)
{
if($startdate >= $lastdate)
{
return $counter;
}
else
{
return daycount($day, strtotime("next ".$day, $startdate), ++$counter);
}
}
$start_date = "2013-05-01";
$last_date = "2013-08-30";
echo "Tuesday Count - ".daycount("tuesday", strtotime($start_date), strtotime($last_date));
echo "<br/>";
echo "Thursday Count - ".daycount("thursday", strtotime($start_date), strtotime($last_date));
Try with this
$startDate = strtotime($start_date);
$endDate = strtotime($last_date);
while ($startDate < $endDate) {
echo date('Y-m-d', $startDate ). "\n";
// Give the condition to find last Tuesday
$startDate = strtotime( 'next Tuesday', $startDate );
}
With DateTime:
$start_date = "2013-05-01";
$last_date = "2013-08-30";
$start = new DateTime($start_date);
$clone = clone $start;
$start->modify('next thursday');
$thursday=$start->format('Y-m-d');
$clone->modify('next tuesday');
$tuesday=$clone->format('Y-m-d');
echo $thursday; //2013-05-02
echo $tuesday; //2013-05-07
We need to objects because if in interval tuesday is before thursday we will have next tuesday. But you can modify little code to use one object.
With the help of few php date functions this can be solved easily..
<?php
// Create the from and to date
$start_date = strtotime("2013-05-01");
$last_date = strtotime("2013-08-30");
// Get the time interval to get the tue and Thurs days
$no_of_days = ($last_date - $start_date) / 86400; //the diff will be in timestamp hence dividing by timestamp for one day = 86400
$get_tue_thu_days = array();
// Loop upto the $no_of_days
for($i = 0; $i < $no_of_days; $i++) {
$temp = date("D", $start_date);
if($temp == "Tue" || $temp == "Thu") {
$get_tue_thu_days[] = date("D/M/Y", $start_date); //formating date in Thu/May/2013 formate.
}
$start_date += 86400;
}
print_r($get_tue_thu_days);
if you have a reference date which you know is a tuesday/thursday you can find days which are a multiple of 7 days from your reference date, these days will always be the same day of the week.