is it possible to use datetime in an array? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Is it possible to use DateTime to grab every date from now till one week ago and than make an array, for example
1-4-2014
1-3-2014
1-2-2014
And so on
Currently this is my code
<?php
$datetime = new DateTime();
$datetime->format('Y-m-d');
$arr = array(/* diverse dates */);
foreach ($to_remove as $item)
{
$is_smaller = ($to_remove->format('U') <= $datetime->format('U'));
if ($is_smaller)
{
$arr = array_filter($arr, function($item) use ($to_remove) {
return !preg_match("/$to_remove by /", $item);
});
}
}
Basically I need it to check the current date and the dates from one week ago and then remove the string from the array.

Yes, you can use DateTime class and DateInterval with DatePeriod:
$now = new DateTime( "now");
$yourInterval= new DateInterval( 'P1D'); //here you set interval per one day
$yourPeriodOfSevenDays= new DatePeriod( $now, $yourInterval, 7); // here you will set to what piriod of time get inerval
foreach($yourPeriodOfSevenDays as $day) {
$date = $day->format( 'd-m-Y');
$resultArray[] = $date ;
}
Now you will have all dates in array
array(8) { [0]=> string(10) "04-01-2014" [1]=> string(10) "05-01-2014" [2]=> string(10) "06-01-2014" [3]=> string(10) "07-01-2014" [4]=> string(10) "08-01-2014" [5]=> string(10) "09-01-2014" [6]=> string(10) "10-01-2014" [7]=> string(10) "11-01-2014" }

This is the simplest way I can think of:-
$lastWeek = new \DateTime('-7 days');
$interval = new \DateInterval('P1D');
$period = new \DatePeriod($lastWeek, $interval, new \DateTime());
var_dump(iterator_to_array($period));
See it working.
Even simpler, if you like one liners:-
$period = new \DatePeriod(new \DateTime('-7 days'), new \DateInterval('P1D'), new \DateTime());
var_dump(iterator_to_array($period));
See it working.
Then again, you can use a DatePeriod object in a foreach loop, so you may not need an array:-
$period = new \DatePeriod(new \DateTime('-7 days'), new \DateInterval('P1D'), new \DateTime());
foreach($period as $day){
echo $day->format('Y-m-d');
}
See it working
Reference http://php.net/datetime

You could use DateTime::add.
$dateTime = new DateTime("now");
$dateInterval = new DateInterval('P1D');
$days = 7;
$resultArray = array();
for($i=0 ; $i<$days ; $i++){
$dateTime->add($dateInterval);
$resultArray[] = $dateTime->format('d-m-Y');
}
Result:
array(7) {
[0]=> string(10) "05-01-2014"
[1]=> string(10) "06-01-2014"
[2]=> string(10) "07-01-2014"
[3]=> string(10) "08-01-2014"
[4]=> string(10) "09-01-2014"
[5]=> string(10) "10-01-2014"
[6]=> string(10) "11-01-2014"
}
Edit:
My fault, i overread the description "one week ago".
Also you can use DateTime::sub

Related

I need help about getting list of days from a week number with PHP

I want to create a function to get a list of days from a week number and a year as parameters.
I've tried to write this following function, which only works when my week number is greater than 10.
public function getDaysofWeek(int $year, int $week){
// ...
$days = array();
for($d=1; $d<8; $d++) {
$days[] = date('d/m/Y', strtotime($year."W". $week .$d));
}
var_dump($days);
// ...
For the week 37 of 2019 (week of today), i got this (actually the correct result) :
array(7) { [0]=> string(10) "09/09/2019"
[1]=> string(10) "10/09/2019"
[2]=> string(10) "11/09/2019"
[3]=> string(10) "12/09/2019"
[4]=> string(10) "13/09/2019"
[5]=> string(10) "14/09/2019"
[6]=> string(10) "15/09/2019" }
But when my week number is less than 10, i got this (here, week 05 of 2019):
array(7) { [0]=> string(10) "16/12/2019"
[1]=> string(10) "23/12/2019"
[2]=> string(10) "30/12/2019"
[3]=> string(10) "01/01/1970"
[4]=> string(10) "01/01/1970"
[5]=> string(10) "01/01/1970"
[6]=> string(10) "01/01/1970" }
I can't understand why this problem is happening, does someone have an
explanation or solution ?
The problem is that as you are using an integer for the week, when you build this into the date in
$days[] = date('d/m/Y', strtotime($year."W". $week .$d));
You end up with an error as the date isn't formed correctly (2019W5), you need to make sure you have a 2 digit week.
This just formats the week to ensure it comes out as 2019W05...
$days[] = date('d/m/Y', strtotime($year."W".
sprintf("%02d", $week) .$d));

PHP Date + days

I got something like this in MyBB and I want add 5 days to date ($datetime1) with one should be stored in $nowPlus5D.
Moreover display in $leeft variable how much days, hours, minutes left. difference between (day bought + 5days ) - datenow
define("IN_MYBB", 1);
require_once "global.php";
$data_zakupu = $db->query("
SELECT timestamp
FROM ".TABLE_PREFIX."subs
WHERE txn_id <> '' AND uid=".$mybb->user['uid']." ORDER BY lid DESC LIMIT 1;
");
$dat = $db->fetch_field($data_zakupu,"timestamp");
$date_buy = date('d-m-Y H:i:s', $dat); // added h:i:s
// Total bought
echo '<br><hr>';
echo 'Bought date - ' . $date_buy;
echo '<br>';
$datetime2 = new DateTime('now');
$datetime1 = new DateTime($date_buy);
$interval = $datetime1->diff($datetime2);
$nowPlus5D = $datetime1->add(new DateInterval('P5D'));
echo '<hr><br>';
echo 'Expiration date - ' . $nowPlus5D->format('%a days, %h hours, %i, minutes');
echo '<br>';
$leeft = $nowPlus5D->diff($datetime1);
var_dump($leeft);
echo '<br>';
echo $left->format('%a days, %h hours, %i, minutes');
and I got that
Bought date - 20-12-2018 18:20:48
Expiration date - %pm 25pm1848, %06 062018000000Tue, 25 Dec 2018 18:20:48 +010048, %20, 12201200000031Europe/Warsaw48
object(DateInterval)#14 (15) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(0) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> int(0) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) }
Fatal error: Call to a member function format() on integer in /stackoverflow.php on line 42
Your main issue is you are confusing a couple objects. Specifically DateInterval with DateTime. Formatting is one thing that differs.
<?php
$date_buy = '2018-12-15 10:05:22';
$datetime2 = new DateTime('now');
$datetime1 = new DateTime($date_buy);
$interval = $datetime1->diff($datetime2);
$nowPlus5D = $datetime1->add(new DateInterval('P5D'));
//THIS IS A DATETIME OBJECT, NOT AN INTERVAL! NOTE FORMAT `Y-m-d H:i:s`
echo 'Expiration date - ' . $nowPlus5D->format('d \d\a\y\s, H \h\o\u\r\s, i \m\i\n\u\t\e\s');
var_dump($nowPlus5D);
var_dump($datetime1);
// ^ Notice those are the same? A result of `$nowPlus5D = $datetime1->add(new DateInterval('P5D'));`
// and Intervals then are of course zeros...
$left = $nowPlus5D->diff($datetime1);
echo '<br>';
echo $left->format('%a days, %h hours, %i, minutes');
// could do this...
$left = $nowPlus5D->diff(new \DateTime);
echo $left->format('%a days, %h hours, %i, minutes');
Anyway, think your main confusion was over the two object types. Imagine you can take it from here.

Increment the day value from current day

For example, in my case, i already has this value of array.....
array(1) {
[1]=>
array(1120) {
["2006-02-25"]=>
array(1) {
[0]=>
int(33)
}
["2006-02-20"]=>
array(1) {
[0]=>
int(38)
}
["2006-02-28"]=>
array(1) {
[0]=>
int(46)
}
that result I've got this code
$explodeEndDate = explode(" ",$adEndDate);
$explodeStartDate = explode(" ", $adStartDate);
$StartDate = $explodeStartDate[0];
$NewStartDate = strtotime("$explodeStartDate[0]");
$NewEndDate = strtotime("$explodeEndDate[0]");
$timeDiff = abs($NewEndDate - $NewStartDate);
// 86400 seconds in one day
$NumberDays = $timeDiff/86400;
//convert into int
$NumberDays = intval($NumberDays);
if(array_key_exists($NumberDays, $array[$itemType]) == false){
$array[$itemType][$StartDate] =[$NumberDays];
}
}
what I wanted to achieve is, in the "$StartDate" value which is for example ["2006-02-28"] , I wanted to plus it with the value of it. If we referring back to the figure above for example is
["2006-02-25"]=>
array(1) {
[0]=>
int(33)
so 2006-02-25 is the plus by 33 and the result is 2006-04-01. and after that, i wanted to make the date within that range
If you want to add date so here you go:
Months:
<?php
$date = date('Y-m-d', strtotime("+33 months", strtotime('2006-02-25')));
var_dump($date)
?>
Demo.
Days:
<?php
$date = date('Y-m-d', strtotime("+33 days", strtotime('2006-02-25')));
var_dump($date)
?>
Demo

PHP Date difference

i've the following code:
$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->days;
I don't know why i'm getting 6015 as result.
Try like
$dStart = strtotime('2013-03-15');
$dEnd = strtotime('2013-04-01');
$dDiff = $dEnd - $dStart;
echo date('H:i:s',$dDiff);
or as per your code try with
$dDiff = $dStart->diff($dEnd);
$date->format('d',$dDiff);
echo $dDiff->days;
if you want diff in days try with this also
echo floor($dDiff/(60*60*24));
Try this-
$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%d days')
Check PHP
Please check demo link
use this
$datetime1 = date_create('2013-03-15');
$datetime2 = date_create('2013-04-01');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
I prefer something like:
function days_diff($first_date, $second_date)
{
$later = new DateTime($second_date);
$then = new DateTime($first_date);
return $later->diff($then)->format('a');
}
I got the same 6015 days on PHP 5.3.0 and found the solution using var_dump().
My exact code is here:
$timestring = "Thu, 13 Jun 2013 14:05:59 GMT";
date_default_timezone_set('GMT');
$date = DateTime::createFromFormat('D, d M Y G:i:s T', $timeString);
$nowdate = new DateTime("now");
$interval = $date->diff($nowdate);
Now if I do a var_dump($interval), the result is:
object(DateInterval)#5 (8) {
["y"]=>
int(0)
["m"]=>
int(0)
["d"]=>
int(0)
["h"]=>
int(19)
["i"]=>
int(45)
["s"]=>
int(33)
["invert"]=>
int(0)
["days"]=>
int(6015)
}
So the hours (h), minutes(i) and seconds (s) are set correctly but there is another property days which remains constant at 6015 and this is what others are getting as a bug. Well, I can't understand where it is getting this value. Again, as per the PHP manual for DateInterval at http://www.php.net/manual/en/class.dateinterval.php, I tried accessing them as properties of an object and things went absolutely fine.
Hence, I get exact result by:
echo (string) $interval->d." days ago";

Months from 2 unixtimestamps

I have 2 timestamps from 2 dates: 01/2012 and 02/2013. The difference between these timestamps is 31795200. The function i've used is:
function unixTimeStampInMonths($timestamp){
$elapsed_minutes = ($timestamp / 60);
$elapsed_hours = ($elapsed_minutes / 60);
$elapsed_days = ($elapsed_hours / 24);
$elapsed_months = floor($elapsed_days / 30);
return $elapsed_months;
}
But there is a problem, the months are rounded to 30 days. What's the best way of calculating the months difference between them?
LE:
The solution suggested by a friend is:
// arguments format: 05/2010
function monthDifferenceBetween2Dates($first, $second){
$expl1 = explode('/', $first);
$expl2 = explode('/', $second);
$months_in_years = ($expl2[1] - $expl1[1] - 1) * 12;
$first_months = 12 - $expl1[0];
$second_months = $expl2[0];
return $months_in_years + $first_months + $second_months;
}
i'm gonna use this. thanks #nickb
Use PHP's DateTime class instead of UNIX timestamps:
$start = DateTime::createFromFormat( 'm/d/Y', '01/01/2012');
$end = DateTime::createFromFormat( 'm/d/Y', '02/01/2013');
$diff = $start->diff( $end);
var_dump( $diff);
Will output:
object(DateInterval)#3 (8) {
["y"]=>
int(1)
["m"]=>
int(1)
["d"]=>
int(0)
["h"]=>
int(0)
["i"]=>
int(0)
["s"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
int(397)
}
So, to calculate total months, we can do:
$months = $diff->y * 12 + $diff->m;
Which will print 13. Demo

Categories