array_sum result is negative - php

I have an array like so
array (size=5107)
0 => int 421
1 => int 996
2 => int 1555
3 => int 399
4 => int 57914
5 => int 57245
6 => int 7176
7 => int 7166
8 => int 5987
This array is being generated by pulling some timestamps from a database, comparing them and then getting the difference in seconds like so;
$start_date = new DateTime($startdate);
$since_start = $start_date->diff(new DateTime($closedate));
$diff = strtotime($closedate) - strtotime($startdate);
I then want to get the average of the array, but whenever I do a array_sum($array); the result is always negative and I'm not sure why. What am I misunderstanding here?
If I change
$diff = strtotime($closedate) - strtotime($startdate);
To
$diff = strtotime($startdate) - strtotime($closedate);
The array_sum($array); results in a positive value but all the array values are negative but all the results are the same.

You should get the absolute value:
$diff = abs(strtotime($closedate) - strtotime($startdate));

Related

String timestamp to int, make a DateTime with it afterwards in PHP

I want to know if a timestamp stored in my database as a bigint (I'm using mariaDB) is already old comparing it to the current date, there's one example:
I have this timestamp stored in my db = 1560499685530 but for some reason, it is a string when I fetch it from my db so I got this error when trying to set its timestamp (setTimestamp($timestamp))
DateTime::setTimestamp() expects parameter 1 to be integer, string
given
I tried using intval but my timestamp seems to be too long to be int because when I use inval it returns another int, smaller than mine, I guess that's the PHP int cap
I want my PHP to print if it's already an old date comparing it to the current date and wrote this code
$qBloqueo = mysqli_query($conn, "SELECT * FROM dates WHERE idUsuario = '$idUsuario'") or die(mysqli_error($conn));
$timestamp = mysqli_fetch_assoc($qBloqueo);
$timestamp = intval($timestamp['timestamp']); // Getting the timestamp from my db which is a string, still dunno why, in my db it's a bigint
$today = new DateTime();
$expireDate = new DateTime();
$expireDate->setTimestamp($timestamp);
if($today->format("Y-m-d") > $expireDate->format("Y-m-d")) {
print('Old date ^u^');
} else {
print('Not yet');
}
How can I use a timestamp to make a date obj without been a int or there is any way to convert it from a string to int? I just want to make a date from a string timestamp so I could compare it to the current date
If only type is concern then you can type cast variable like:
$timestamp = (int) $timestamp['timestamp'];
If you're looking for difference between two times
<?php
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
?>
Output :
1 second(s)
Now to find difference between two timestamps
/* PHP/5.5.8 and later */
$start = new DateTimeImmutable('2016-04-20 00:37:15');
$end = $start->modify('+7 days');
$diff = $end->diff($start);
print_r($diff);
Output :
DateInterval Object ( [y] => 0 [m] => 0 [d] => 7 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 7 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
To convert date timestamp into millisecond
$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;
print_r($time_in_ms);
Output :
1458657000000
You can convert both times into millisecond and find which one is greater.
I hope this helps in some way

PHP's date functions: converting from weeknumber back to month

Given the information below:
Year: 2012
Weeknumber: 4
Dayname: TUE
How can i convert this to a valid date like 2012-01-12 (YYYY-MM-DD) using PHP's date functions?
Thanx
The DateTime class can't do this, but the function strptime can.
$d = strptime('TUE 4 2012', '%a %W %Y');
var_dump($d);
That returns an array:
array
'tm_sec' => int 0
'tm_min' => int 0
'tm_hour' => int 0
'tm_mday' => int 24
'tm_mon' => int 0
'tm_year' => int 112
'tm_wday' => int 2
'tm_yday' => int 23
'unparsed' => string '' (length=0)
Note that tm_year contains the number of years since 1900 and tm_month is 0-based, not 1-based. So this does represent 2012-01-24, which is correct.
Use this function:
function get_date($year,$week,$day,$start_sunday=false){
$day_array = array('Mon'=>1,'Tue'=>2,'Wed'=>3,'Thu'=>4,'Fri'=>5,'Sat'=>6,'Sun'=>($start_sunday?0:7));
$month_array = array(31,($year%4==0?29:28),31,30,31,30,31,31,30,31,30,31);
$week *= 7;
$month = 1;
for($i=0;$i<count($month_array);$i++){
if($week-$month_array[$i]<=0){
break;
}
$week -= $month_array[$i];
$month++;
}
$format = "$year $month $week";
$date = date_create_from_format("Y m j",$format);
$date_num = date_format($date,"D");
$curr = $day_array[ucfirst(strtolower($day))]-$day_array[$date_num];
$got_date = strtotime("$curr ".($curr==1||$curr==-1?"day":"days"),strtotime(date_format($date,"Y-m-j")));
return $got_date;
}
where $start_sunday should be true if week starts from sunday
$year is the year
$week is week number
$day is short weekday name i.e.mon,tue,wed,....
this function will get you a date form the given format.
Enjoy............

Strange behaviour of PHP DateTime Class

I'm trying to get the time difference in milliseconds.
$_SESSION['startTime'] = time();
$to_time = time();
//I call the code from here after a delay, say 4 seconds
$from_time = $_SESSION['startTime'];
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
print_r( $d1->diff($d2));
I print the result after 4 seconds and the result is somewhat like this:
DateInterval Object
(
[y] => 4 //---- Problem, this value should be +
[m] => 0 // |
[d] => 0 // |
[h] => 0 // |
[i] => 0 // |
[s] => 0 //<-here-----------------------------+
[invert] => 1
[days] => 1461
)
[s] should have been 4. why the 4 is in the year section?
What am I doing wrong?
UPDATE - Solved
$to_time = (microtime(true));
$from_time = ( $_SESSION['startTime']);
$diff = $to_time - $from_time;
print $diff;
Prints
3.xxxxxx
You must specify the formatting. You're sending in a unix timestamp into DateTime, therefor:
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
Becomes
$d1 = new DateTime('#'.$from_time);
$d2 = new DateTime('#'.$to_time);
The # symbol tells DateTime that I'm using a Unix Timestamp.
The constructor for DateTime accepts a string as a parameter not a timestamp, which is why you are seeing the "strange behaviour".
You need to expressly set the timestamp after insantiating a DateTime object:-
$from_time = $_SESSION['startTime'];
$d1 = new DateTime();
$d1->setTimestamp($from_time);

Calculating difference between dates

I need your help in how to subtract the last_modified and the final_manuscript_date in the following array:
Array (
[chapters_id] => 10736
[last_modified] => 2010-12-21 15:01:55
[steps_id] => 3
[sub_step_id] => 0
[steps_position] => 1
[final_manuscript_date] => 2010-09-27
)
So I can in this case get a value of N days between the dates 2010-12-21 and 2010-09-27?
Can't you simply do:
$diff = strtotime($arr["final_manuscript_date"]) - strtotime($arr["last_modified"]);
$days = $diff / 84600; // to get # of days, you can round them off or use ceil/floor
If you have 5.3+:
$date1 = new DateTime("2010-09-27");
$date2 = new DateTime("2010-12-21");
$interval = $date1->diff($date2);
echo $interval->d //returns days.
Have you checked strtotime?
http://php.net/manual/en/function.strtotime.php

Calculate number of days between two given dates

Can anyone correct the error in my script to calculate the number of days between 2 dates.
The dates have been input through a form, the variable info is as followed:
[departon] => Array ( [0] => 1 [1] => June [2] => 2011 )
[returnon] => Array ( [0] => 31 [1] => June [2] => 2011 )
I have written the code to calculate these dates, but its not calculating the day, it just outputs 0.
<?php
$first_date = mktime(12, 0, 0, $_POST['departon'][1], $_POST['departon'][0], $_POST['departon'][2]);
$second_date = mktime(12, 0, 0, $_POST['returnon'][1], $_POST['returnon'][0], $_POST['returnon'][2]);
$days = $second_date-$first_date;
echo floor($days/60/60/24) . " days";
?>
Help would be much appreciated.
The easiest way is by using datetimes.
Consider this:
var_dump(new DateTime('1 July 2007'));
$a = new DateTime('1 July 2007');
$b = new DateTime('1 June 2001');
var_dump($a->diff($b));
The var_dump will allow you to see the different kind of time you can extract from it.
object(DateInterval)[3]
public 'y' => int 6
public 'm' => int 1
public 'd' => int 0
public 'h' => int 0
public 'i' => int 0
public 's' => int 0
public 'invert' => int 1
public 'days' => int 2221
You can convert your array to a date time very easily by using
$date = new DateTime(join(" ",$array));
$date2 = new DateTime(join(" ",$array2));
$diff = $date->diff($date2);
Here's an easy way:
$depart = strtotime(implode(' ', $_POST['departon']));
$return = strtotime(implode(' ', $_POST['returnon']));
$diff = floor(($return - $depart) / (60 * 60 * 24));
Note: there's only 30 days in June.
The mktime documentation specifies a number for the month, so you'd need to convert 'June' to '6'.

Categories